上节: 编写一个loader
目录:
插件会运行在webpack的各个生命周期,我们设计一个插件时,必须确定这个插件的执行时机。
webpack的生命周期很多,参考:https://webpack.js.org/api/co...
现在写个简单的插件,需求是在打包完成后,额外输出一个叫copyRight.txt的文件
根目录下新建plugins/copy-right.plugin.js:
module.exports = class CopyRightPlugin {
constructor(params) {
this.name = (params && params.name) || 'Madao';
}
apply(compiler) {
/*
compiler.hooks:webpack生命周期
*/
const that = this;
// 资源输出到 output 目录前执行, 是个异步钩子
compiler.hooks.emit.tapAsync('CopyRightPlugin', (compilation, cb) => {
// compilation.assets 打包后的内容
// debugger;
compilation.assets['copyRight.txt'] = {
source() {
// 返回文件内容
return 'copyright by ' + that.name
},
size() {
// 文件大小
return 30
}
}
cb();
});
}
}
es6的类就不多说了,然后再配置中引用。
webpack/webpack.prod.js:
const CleanWebpackPlugin = require('clean-webpack-plugin');
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyRightPlugin = require('../plugins/copy-right.plugin');
module.exports = merge(baseConfig, {
mode: 'production',
output: {
filename: '[name].[contenthash:10].js'
},
devtool: 'cheap-module-source-map',
module: {
rules: [{
test: /\.less$/,
use: [{
loader: MiniCssExtractPlugin.loader,
}, 'css-loader', 'postcss-loader', 'less-loader']
}]
},
plugins: [
new CopyRightPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
}),
new CleanWebpackPlugin()
],
optimization: {
splitChunks: {
chunks: 'all'
}
}
});
然后npm run build, 查看输出目录:
下节:手动配置vue-cli上
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。