注意❗
注意版本 node >= 18.12.0
用于将单个文件或整个目录复制到构建目录。
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'docs'), // 源文件路径
to: path.resolve(__dirname, 'dist'), // 目标文件路径
toType: 'dir',
filter: function (filePath) {
// 只拷贝 .md 文件
return /\.(md|html|css)$/.test(filePath);
},
globOptions:{
ignore:[
'**/index.html'
]
}
}
],
}),
toType: 'dir'
是按目录结构进行拷贝。/\.(md|html|css)$/.test(filePath)
是只拷贝md
、html
、css
源码实现
const fs = require('fs-extra');
const path = require('path');
class CopyWebpackPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.emit.tapAsync('CopyWebpackPlugin', (compilation, callback) => {
this.options.forEach(option => {
fs.copySync(option.from, path.join(compiler.options.output.path, option.to));
});
callback();
});
}
}
module.exports = CopyWebpackPlugin;
使用方法:
const CopyWebpackPlugin = require('./CopyWebpackPlugin');
module.exports = {
// ...
plugins: [
new CopyWebpackPlugin([
{ from: 'src/assets', to: 'assets' },
]),
],
};