plugins
插件是 webpack 的支柱功能. 插件的目的在于解决 loader 无法实现的其他事
剖析
webpack 插件是一个具有 apply 属性的 JavaScript 对象. apply 属性会被 webpack compiler 调用, 并且 compiler 对象可在整个编译生命周期访问
1 2 3 4 5 6 7 8 9
| const pluginName = 'ConsoleLogOnBuildWebpackPlugin'
class ConsoleLogOnBuildWebpackPlugin { apply(compiler) { compiler.hooks.run.tap(pluginName, (compilation) => { console.log('webpack 构建过程开始!') }) } }
|
compiler hook 的 tap 方法的第一个参数,应该是驼峰式命名的插件名称。建议为此使用一个常量,以便它可以在所有 hook 中复用。
用法
由于插件可以携带参数/选项,你必须在 webpack 配置中,向 plugins 属性传入 new 实例。
根据你的 webpack 用法,这里有多种方式使用插件。
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const HtmlWebpackPlugin = require('html-webpack-plugin') const webpack = require('webpack') const path = require('path')
const config = { 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.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }), ], }
module.exports = config
|
Node API
1 2 3 4 5 6 7 8 9
| const webpack = require('webpack') const configuration = require('./webpack.config.js')
let compiler = webpack(configuration) compiler.apply(new webpack.ProgressPlugin())
compiler.run(function (err, stats) { })
|