实现一个plugin

通过plugin拷贝额外资源

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const fs = require('fs');
const path = require('path');
const glob = require("glob")
const {promisify} = require('util');
const readFile = promisify(fs.readFile);

const {RawSource} = require('webpack').sources;
const { validate } = require('schema-utils');

const schema = {
"type": 'object',
"properties": {
"from": {
"type": 'string',
},
"to": {
"type": 'string',
},
"ignore": {
"type": 'array',
},
// 不允许有其他属性
"additionalProperties": false
}
};

class CopyfilePlugin {
constructor(options={}){
// 验证参数
validate(schema, options);
this.options = options;
}
apply(compiler) {
compiler.hooks.thisCompilation.tap('CopyfilePlugin',(compilation)=>{
compilation.hooks.additionalAssets.tapAsync('CopyfilePlugin', (callback) => {

const {from,to,ignore} = this.options;
// 获取系统运行时的文件目录
const {context} = compiler.options;
// 获取from的绝对路径
const fromRelative = path.resolve(context,from,'*.*');

// 获取from文件夹的文件
// 排除不需要的文件
const filePaths = glob.sync(fromRelative,{
ignore:['**/index.html']
})
filePaths.forEach(async (filePath)=>{
const file = await readFile(filePath);
// 获取文件名称
const filename = path.basename(filePath);
// 添加额外的打包资源
compilation.assets[filename] = new RawSource(file);
})

callback()
});
})
}
}

module.exports =CopyfilePlugin;
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信