插件是 webpack 的支柱功能。webpack 自身也是構建於,你在 webpack 配置中用到的相同的插件系統之上!目的在於解決 loader 無法實現的其他事。
剖析
webpack 插件是一個具有 apply
屬性的 JavaScript 對象。apply
屬性會被 webpack compiler 調用,並且 compiler 對象可在整個編譯生命週期訪問。
ConsoleLogOnBuildWebpackPlugin.js
const pluginName = 'ConsoleLogOnBuildWebpackPlugin'; class ConsoleLogOnBuildWebpackPlugin { apply(compiler) { compiler.hooks.run.tap(pluginName, compilation => { console.log("webpack 構建過程開始!"); }); } }
compiler hook 的 tap 方法的第一個參數,應該是駝峯式命名的插件名稱。建議爲此使用一個常量,以便它可以在所有 hook 中複用。
用法
由於插件可以攜帶參數/選項,你必須在 webpack 配置中,向 plugins
屬性傳入 new
實例。
根據你的 webpack 用法,這裏有多種方式使用插件。
配置
// webpack.config.js const HtmlWebpackPlugin = require('html-webpack-plugin'); //通過 npm 安裝 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
const webpack = require('webpack'); //訪問 webpack 運行時(runtime) const configuration = require('./webpack.config.js'); let compiler = webpack(configuration); compiler.apply(new webpack.ProgressPlugin()); compiler.run(function(err, stats) { // ... });