1、分類
2、執行順序
配置類型
執行順序是 loader1>loader2>loader3
3、使用方式
自己的第一個loader
同步loader
/*** loader 就是一個函數* 當webpack 解釋資源時, 會調用相應的loader去處理* loader 接收到文件內容作為參數,返回文件內容* @param {*} content 文件內容* @param {*} map SourceMap* @param {*} meta 別的loader 傳遞過來的數據*/
module.exports = function(content, map, meta){console.log('main.js 傳過來的數據', content);return content
}/*** 當需要傳遞參數給其他 loader 的loader 寫法*/// module.exports = function (content,map, meta) {
// // 第一個參數: err 代表是否有錯誤
// // 第二個參數:content 處理后的內容
// // 第三個參數: source-map 繼續傳遞source-map
// // 第四個參數:meta 給下一個loader傳遞參數
// this.callback(null,content,map,meta);
// }
?會在vscode 終端看到
異步loader (同步loader不能調用異步方法)
module.exports = function(content, map, meta){const callback = this.async()setTimeout(()=>{console.log('異步操作');callback(null, content, map, meta)}, 1000)
}
?raw loader,處理圖片、svg等時會用到
// 同步異步操作均可以
module.exports = function(content, map, meta){console.log('raw-loader Buffer數據流', content);return content
}module.exports.raw = true
目前 只有 main.js 文件
console.log('hello word');
patch loader
執行順序
// pitch-loader1.js
module.exports = function(content, map, meta){console.log('pitch-loader1');return content
}module.exports.pitch = function(content, map, meta){console.log('pitch1');
}// pitch-loader2.js
module.exports = function(content, map, meta){console.log('pitch-loader2');return content
}module.exports.pitch = function(content, map, meta){console.log('pitch2');
}// pitch-loader.js
module.exports = function(content, map, meta){console.log('pitch-loader3');return content
}module.exports.pitch = function(content, map, meta){console.log('pitch3');
}
webpack.config.js 配置
打印結果
如果patch中有return 則不糊執行后續的操作,而是直接返回到上一個loader執行,如果沒有就不用執行,下面是在loader中有返回值的意思,直接返回到loader執行操作
4、loader Api
this.getOptions 獲取options
?schema.json
打包后文件中就會多出坐著相關信息
5、簡單重寫一下常用的部分loader
babel-loader
const babel = require('@babel/core')
const schema = require("./schema.json")module.exports = function(content, map, meta){// 獲取webpack 使用這個loader 時的options配置項const callback = this.async()const options = this.getOptions(schema)babel.transform(content, options, function(err, result){if(err) callback(err)else callback(null, result.code)})
}
schema.json
{"type":"object","properties":{"presets":{"type": "array"}},"additionalProperties": false
}
webpack 中的使用
file-loader? (使用到this.emitFile函數)
?webpack 配置
stylle-loader
主要作用,通過js代碼創建一個style標簽 ,然后將樣式代碼加進去
這里? module.exports = function(){} 空函數即可
如果,想要更深一步學習loader, 可以去看看常用的loader的源碼