webpack loader开发
同步loader
const loaderUtils = require('loader-utils');
/**
*
* @param {*} content 文件信息
* @param {*} map 文件映射信息
* @param {*} meta
* source是输入的内容
* sourceMap是可选的
* meta是模块的元数据,也是可选的
*/
module.exports = function(content, map, meta) {
console.log(content);
// const options = loaderUtils.getOptions(this);
debugger;
return content.replace(/world/g, 'Loader');
}
module.exports.pitch = function() {
console.log('pitch1')
}
module.exports = function(source, map, meta) {
// 第一个参数为错误信息
this.callback(null, source, map, meta);
}
loader的执行顺序,如有三个loader
{
test: /\.js$/,
use: ['loader1', 'loader2', 'loader3']
}
loader1.pitch->loader2.pitch->loader3.pitch->loader3->loader2->loader1
异步loader
module.exports = functions(source, map, meta) {
const callback = this.async();
setTimeout(() => {
callback(null, source, map, meta);
}, 1000);
}
设置loader的解析路径
webpack.config.js 根
module.exports = {
modules: [
'node_modules',
path.resolve(__dirname, 'config/loaders')
]
}
设置并校验loader的参数配置
module.exports = {
modules: {
rules: [
{
loader: 'myloader',
options: {
name: 'zengwe'
}
}
]
}
}
const { getOptions } = require('loader-utils');
const { validate } = require('schema-utils');
const schema = require('./schema.json');
module.exports = function(source, map, meta) {
const options = getOptions(this);
validate(schema, options, {
name: 'myloader'
});
return content;
}
校验规则文件schema.json
{
"type": "object",
"properties": {
"name": {
"type": "string",
"descript": "name description"
}
},
"additionalProperties": true
}
additionalProperties表示是否可以添加别的属性