webpack Plugins

是什么

Plugins 本质上是一个包含 apply 方法的类,apply 会被 webpack compiler 调用。

apply 方法中可以访问到 compiler 对象,进而对其挂上钩子。

1
2
3
4
5
6
7
8
9
10
11
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

class ConsoleLogOnBuildWebpackPlugin {
apply(compiler) {
compiler.hooks.run.tap(pluginName, compilation => {
console.log('webpack 构建过程开始!');
});
}
}

module.exports = ConsoleLogOnBuildWebpackPlugin;

compiler hook 的 tap 方法的第一个参数,应该是驼峰式命名的插件名称。建议为此使用一个常量,以便它可以在所有 hook 中重复使用。

有什么作用

plugin 可于执行更广泛的任务,如 打包优化、资源管理、注入环境变量。

使用方法

  1. 如果是外部 Plugins,则需要先安装
  2. 然后在 webpack 中 require 进来
  3. 通过 new 创建插件实例,将其添加到 plugins 数组中
  4. 可根据不同目的多次使用同一个插件
  5. 使用对象给插件实例传递参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
const webpack = require('webpack'); // 访问内置的插件
const path = require('path');

module.exports = {
entry: './path/to/my/entry/file.js',
output: {
filename: 'my-first-webpack.bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: 'babel-loader'
}
]
},
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
};