官网链接:https://webpack.js.org/concepts/plugins/
plugins 是 webpack 的骨干,它们用于做一些 loaders 做不到的事情
一、简述 Plugins
一个 plugin 是一个有 apply 方法的 JavaScript 对象,这个 apply 方法被 webpack 编译器调用,让它进入整个编译生命周期中。
下面是一个例子
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';class ConsoleLogOnBuildWebpackPlugin {apply(compiler) {compiler.hooks.run.tap(pluginName, (compilation) => {console.log('The webpack build process is starting!!!');});}}module.exports = ConsoleLogOnBuildWebpackPlugin;
二、用法
一旦 plugins 能够携带参数,你必须在 webpack 的 plugins 属性中 new 一个实例
使用 plugins 的方式有多种
- Configuration
- Node API
1. Configuration
const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npmconst webpack = require('webpack'); //to access built-in pluginsconst 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' }),],};
ProgressPlugin用于自定义在编译期间如何报告进度HtmkWebpackPlugin将生成一个 HTML 文件,并有个 script 标签指向my-first-webpack.bundle.js
2. Node API
当使用 Node API 时,将把 plugins 传递给配置中的 plugins 属性
const webpack = require('webpack'); //to access webpack runtimeconst configuration = require('./webpack.config.js');let compiler = webpack(configuration);new webpack.ProgressPlugin().apply(compiler);compiler.run(function (err, stats) {// ...});
「@浪里淘沙的小法师」
