1. 创建一个简单的loader
所谓 loader 只是一个导出为函数的 JavaScript 模块。loader runner 会调用这个函数,然后把上一个 loader 产生的结果或者资源文件(resource file)传入进去。函数的 this 上下文将由 webpack 填充。
假设我们现在有一个index.js:
//index.js
console.log("hello world")
在不对js文件进行额外处理时对其进行打包,得到/dist/main.js
//main.js
...
/***/ (function(module, exports) {
eval("console.log(\"hello world\")\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ })
...
我们希望借助loader使js文件中要输出的hello world
转换为hello js
,像上文所说,一个loader就是一个导出为函数的JavaScript模块。
创建replaceLoader.js,现在的文件目录结构:
//replaceLoader.js
//使用声明式函数而不是箭头函数,因为在该函数中我们需要使用this
module.exports = function (source){
return source.replace('world','js')
}
然后我们使用replaceLoader对js文件进行处理。
修改webpack.config.js:
...
module: {
rules: [{
test: /\.js/,
use: [
path.resolve(__dirname,'./loader/replaceLoader')
]
}]
}
...
重新打包,查看此时生成的 main.js:
...
/***/ (function(module, exports) {
eval("console.log(\"hello js\")