实现一个loader

WEEBPACK LOADER

简单loader

配置webpack.config,webpace5提供默认的entryoutput所以无需配置

1
2
3
4
5
6
7
8
9
10
11
12
13
module.exports = {
module:{
rules:[{
test:/\.js$/,
use:['my-loader','my-loader1','my-loader2']
}]
},
mode:'production',
// webpack5 提供resolveLoader可以配置loader的查找目录
resolveLoader: {
modules: ['node_modules',path.resolve(__dirname,'loader')],
},
}

实现loader loader/my-loader loader/my-loader1 loader/my-loader2

1
2
3
4
5
6
7
8
9
10
11
// 同步方法在loader解析时执行
// 也就是use数组中的loader从右向左执行
module.exports = function(content){
console.log(111);
return content;
}
// pitch 方法在loader加载时执行
// 也就是use数组中的loader从左向右执行
module.exports.pitch = function(){
console.log('p111')
}

同步loader和异步loader

同步写法

1
2
3
module.exports = function(content){
this.callback(null,content);
}

异步写法,仍然按顺序依次执行,不会改变loader执行顺序

1
2
3
4
5
6
module.exports = function(content){
var callback = this.async();
setTimeout(()=>{
callback(null,content)
},3000)
}

获取loader的options

为loader添加options

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
module.exports = {
module:{
rules:[{
test:/\.js$/,
use:[{
loader:'my-loader',
options:{
test:'1231'
}
},'my-loader1','my-loader2']
}]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const  { getOptions }  = require('loader-utils');
const { validate } = require('schema-utils');

const schema = {
type: 'object',
properties: {
test: {
type: 'string',
}
}
};

module.exports = function(content){
const options = getOptions(this);

console.log(options);
validate(schema, options, {
// 需要校验的loader名称
name: 'my-loader',
baseDataPath: 'options',
});

this.callback(null,content);
}

实现一个loader

添加webpack.config.json配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const path = require('path');

module.exports = {
module:{
rules:[{
test:/\.js$/,
loader:'babelLoader',
options:{
"presets": ["@babel/preset-env"]
}
}]
},
mode:'production',
resolveLoader: {
modules: ['node_modules',path.resolve(__dirname,'loader')],
},
}

loader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const  { getOptions }  = require('loader-utils');
const { validate } = require('schema-utils');
const {promisify} = require('util')
const babel = require('@babel/core');

const schema = {
type: 'object',
properties: {
persets:{
type:'array'
}
}
};

module.exports = function(content){
const options = getOptions(this);
const callback = this.async();

validate(schema, options, {
// 需要校验的loader名称
name: 'babelLoader',
baseDataPath: 'options',
});

console.log(options);


const transfrom = promisify(babel.transform);
transfrom(content,options)
.then(({code}) =>callback(null,code))
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信