根目录下新建replace-hello-loader文件夹执行yarn init -y初始化项目,新建index.js文件作为loader的入口文件。下面的loader实现了将js源码中的 ‘hello’ 替换为 “你好”
// replace-hello-loader/index.js
const loaderUtils = require('loader-utils');
module.exports=function(content){
// 开启缓存,源码没有改变使用缓存
if (this.cacheable) {
this.cacheable();
};
console.log(loaderUtils.getOptions(this));
return content.replace('hello','你好');
};
将loader安装到本地
// 安装
yarn ./add replace-hello-loader
webpack.config.js中添加配置
rules: [
{
test: /\.js$/,
use: {
loader: 'replace-hello-loader',
options: {
sourceMap: true
}
},
enforce: 'pre', //loader前置执行
}
]
- 函数接收一个context参数获取字符串格式的源码
- loader-utils库获取loader的options,这个库要单独安装:yarn add loader-utils
- 通过 this.cacheable()开启缓存