自定义loader
同步loader
module.exports = function (source) {
//source为源代码字符串
const result = source.replace("hello", "你好");
this.callback(null, result); //返回处理后的内容
//依然符合node的错误优先的函数风格
}
异步loader
module.exports = function (source) {
//source为源代码字符串
const result = source.replace("hello", "你好");
const callback = this.async(); //先调用该方法,告诉weibpack该loader是异步的,并返回一个异步的return的callback
setTimeout(() => {
callback(null, result); //异步的返回处理后的内容
//依然符合node的错误优先的函数风格
}, 1000);
}
使用自定义loader
module.exports = {
entry: {
main: "./index.js"
},
resolveLoader: { //配置loader仓库
modules: ["node_modules", "./loaders"] //之后再写loader时无需写loader路径了,我将自定义loader放在了./loaders文件夹中
},
module: {
rules: [{
test: /.js$/,
use: ["my-loader.js"] //使用自定义loader
}]
}
}
向自定义loader传递选项
webpack中参数传递配置
module.exports = {
entry: {
main: "./index.js"
},
resolveLoader: { //配置loader仓库
modules: ["node_modules", "./loaders"] //之后再写loader时无需写loader路径了
},
module: {
rules: [{
test: /.js$/,
use: ["my-loader.js"], //使用自定义loader
options: { //传递配置项
hello: "hi"
}
}]
}
}
自定义loader获取方式
可以使用this.query
获取参数,但是官方更推荐使用loader-utils
工具进行对配置项进行解析,使用npm install loader-utils -D
安装该工具即可
const loaderUtils = require('loader-utils');
module.exports = function (source) {
//source为源代码字符串
// const options = loaderUtils(this); //webpack4使用这种方式获取
const options = loaderUtils.getOptions(this); //webpack5使用这种方式获取
const hello = options.hello; //获取options中的hello属性
const result = source.replace("hello",hello);
this.callback(null, result); //返回处理后的内容
}
Comments NOTHING