plugin – 运行于打包的各个阶段,广播出对应的事件,插件监听事件
场景1:打包前把之前的目录删掉,由clean-webpack-plugin实现
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const config = {
...
plugins: [
new CleanWebpackPlugin()
],
}
module.exports=config
场景2:自动生成工程的index.html,由html-webpack-plugin实现
使用插件之前工程的index.html要自己写,并引入bundle.js。使用插件后,webpack打包时自动在dist下生成index.html,并且支持自定义参数,
// 设置index.html的title、meta
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: '起步',
meta:{
viewport: 'width=device-width'
}
})
],
当需要复杂自定义index.html时,可以写个html模板,模板中使用webpack配置的信息,这样插件生成index.html时会按html模板来做
需要webpack配置文件中指定模板的路径
如果需求要多个html文件,可以并列使用多个new HtmlWebpackPlugin。一般来说会配合多入口打包,不同的html使用不同的打包结果
自己写个plugin
webpack要求plugin是个函数或者包含apply方法的对象
插件就是往webpack生命周期挂载任务函数来实现的