webpack常用插件
- clean-webpack-plugin:自动清理输出目录的插件
yarn add clean-webpack-plugin —dev
const { CleanWebpackPlugin } = require('clean-webpack-plugin')module.exports = {plugins: [new CleanWebpackPlugin()]}
- html-webpack-plugin:webpack自动输出html文件
yarn add html-webpack-plugin -D
const HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = {plugins: [new HtmlWebpackPlugin({template: './src/index.html', // 指定模版文件title: 'webpack'}),new HtmlWebpackPlugin({template: './src/login.html', // 指定模版文件filename: 'login.html', // 指定输出文件名title: 'webpack'}),]}// 在输出的html文件中,可以使用htmlWebpackPlugin中的配置属性:htmlWebpackPlugin.options<div> <%= htmlWebpackPlugin.optoins.title %> </div>
- copy-webpack-plugin:用于复制静态资源,开发阶段最好不要使用该插件
yarn add copy-webpack-plugin -D
const CopyWebpackPlugin = require('copy-webpack-plugin')module.exports = {plugins: [new CopyWebpackPlugin(['pubic/**'])]}
webpack插件机制
webapck plugin是通过钩子机制实现的。webpack在工作过程中会有很多钩子,类似生命周期,不同的生命周期中,可以挂载不同的插件做不同的事情,用以扩展webpack的能力。
webpack要求我们的插件必须是一个函数或者是一个apply方法的对象。
class MyPlugin {// 当webpack启动时会自动调用apply方法,compiler是打包过程中的核心对象,它的上面挂载着不同的生命钩子// 我们可以在不同的生命钩子中做不同的事情apply(compiler) {// emit就是一个生命周期钩子,tap是注册插件的一个方法,其接受两个参数,一个是插件名称,另一个则是函数,即// 即需要干什么compiler.hooks.emit.tap('MyPlugin', (compilation) => {// compilation为打包上下文,即打包结果for(const name in compilation.assets) {console.log(name) // 打包输出的文件名称console.log(compilation.assets[name].source()) // 打包输出文件的资源if (name.endsWith('.js')) {let content = compilation.assets[name].source()const WithoutComments = content.replace(/\/\*\*+\*\//g, '') // 去除注释符号compilation.assets[name] = {source: () => WithoutComments,size: () => WithoutComments.length // webpack要求返回处理后的资源的大小}}}})}}
