webpack常用插件

  • clean-webpack-plugin:自动清理输出目录的插件

yarn add clean-webpack-plugin —dev

  1. const { CleanWebpackPlugin } = require('clean-webpack-plugin')
  2. module.exports = {
  3. plugins: [
  4. new CleanWebpackPlugin()
  5. ]
  6. }
  • html-webpack-plugin:webpack自动输出html文件

yarn add html-webpack-plugin -D

  1. const HtmlWebpackPlugin = require('html-webpack-plugin')
  2. module.exports = {
  3. plugins: [
  4. new HtmlWebpackPlugin({
  5. template: './src/index.html', // 指定模版文件
  6. title: 'webpack'
  7. }),
  8. new HtmlWebpackPlugin({
  9. template: './src/login.html', // 指定模版文件
  10. filename: 'login.html', // 指定输出文件名
  11. title: 'webpack'
  12. }),
  13. ]
  14. }
  15. // 在输出的html文件中,可以使用htmlWebpackPlugin中的配置属性:htmlWebpackPlugin.options
  16. <div> <%= htmlWebpackPlugin.optoins.title %> </div>
  • copy-webpack-plugin:用于复制静态资源,开发阶段最好不要使用该插件

yarn add copy-webpack-plugin -D

  1. const CopyWebpackPlugin = require('copy-webpack-plugin')
  2. module.exports = {
  3. plugins: [
  4. new CopyWebpackPlugin([
  5. 'pubic/**'
  6. ])
  7. ]
  8. }

webpack插件机制

webapck plugin是通过钩子机制实现的。webpack在工作过程中会有很多钩子,类似生命周期,不同的生命周期中,可以挂载不同的插件做不同的事情,用以扩展webpack的能力。
webpack要求我们的插件必须是一个函数或者是一个apply方法的对象。

  1. class MyPlugin {
  2. // 当webpack启动时会自动调用apply方法,compiler是打包过程中的核心对象,它的上面挂载着不同的生命钩子
  3. // 我们可以在不同的生命钩子中做不同的事情
  4. apply(compiler) {
  5. // emit就是一个生命周期钩子,tap是注册插件的一个方法,其接受两个参数,一个是插件名称,另一个则是函数,即
  6. // 即需要干什么
  7. compiler.hooks.emit.tap('MyPlugin', (compilation) => {
  8. // compilation为打包上下文,即打包结果
  9. for(const name in compilation.assets) {
  10. console.log(name) // 打包输出的文件名称
  11. console.log(compilation.assets[name].source()) // 打包输出文件的资源
  12. if (name.endsWith('.js')) {
  13. let content = compilation.assets[name].source()
  14. const WithoutComments = content.replace(/\/\*\*+\*\//g, '') // 去除注释符号
  15. compilation.assets[name] = {
  16. source: () => WithoutComments,
  17. size: () => WithoutComments.length // webpack要求返回处理后的资源的大小
  18. }
  19. }
  20. }
  21. })
  22. }
  23. }