Loader 实现资源加载,Plugin 解决其他自动化工作。

常用插件

清除插件

clean-webpack-plugin 的作用是清除打包的目录。

  1. // webpack.config.js
  2. const { CleanWebpackPlugin } = require('clean-webpack-plugin')
  3. plugins: [
  4. new CleanWebpackPlugin(),
  5. ]

HTML生成插件

html-webpack-plugin 的作用是打包生成 html 文件。这样 html 可以避免硬编码的资源路径。

  1. // webpack.config.js
  2. const HtmlWebpackPlugin = require('html-webpack-plugin')
  3. plugins: [
  4. // 用于生成 index.html
  5. new HtmlWebpackPlugin({
  6. title: 'Webpack Plugin Sample',
  7. meta: {
  8. viewport: 'width=device-width'
  9. }, // 可以设置一些元素
  10. template: './src/index.html' // 可以指定模板
  11. }),
  12. // 用于生成 about.html
  13. new HtmlWebpackPlugin({
  14. filename: 'about.html'
  15. })
  16. ]

复制插件

copy-webpack-plugin 通常用于上线前将静态资源一起打包。

  1. // webpack.config.js
  2. const CopyWebpackPlugin = require('copy-webpack-plugin')
  3. plugins: [
  4. new CopyWebpackPlugin([
  5. // 'public/**'
  6. 'public'
  7. ]), // 拷贝 public 目录下所有文件
  8. new CopyWebpackPlugin({
  9. patterns: [
  10. {
  11. from: { 'public' },
  12. globOptions: {
  13. ignore: ['**/index.html'] // 忽略 public 目录下的index.html
  14. }
  15. }
  16. ]
  17. }), // 拷贝 public 目录下所有文件
  18. ]

开发一个插件

Plugin 实际上是通过钩子机制实现的。Plugin 应该是一个函数或者包含 apply 方法的对象。一般定义一个包含 apply 方法的类。

开发一个清除 “/*…/“这种不必要的注释的插件 MyPlugin。

  1. // webpack.config.js
  2. class MyPlugin {
  3. apply(compiler) {
  4. compiler.hooks.emit.tap('MyPlugin', compilation => {
  5. // compilation => 可以理解为此次打包的上下文
  6. for (const name in compilation.assets) {
  7. // name => 文件名
  8. // console.info(compilation.assets[name].source())
  9. if (name.endsWith('.js')) {
  10. const contents = compilation.assets[name].source() // 获取内容
  11. const withoutComments = contents.replace(/\/\*\*+\*\//g, '') // 清除注释
  12. // 写入处理后的内容
  13. compilation.assets[name] = {
  14. source: () => withoutComments, // 新内容
  15. size: () => withoutComments.length // 新内容的大小
  16. }
  17. }
  18. }
  19. })
  20. }
  21. }
  22. plugins: [
  23. new MyPlugin(),
  24. ]