官网链接:https://webpack.js.org/concepts/plugins/

plugins 是 webpack 的骨干,它们用于做一些 loaders 做不到的事情

一、简述 Plugins

一个 plugin 是一个有 apply 方法的 JavaScript 对象,这个 apply 方法被 webpack 编译器调用,让它进入整个编译生命周期中。

下面是一个例子

  1. const pluginName = 'ConsoleLogOnBuildWebpackPlugin';
  2. class ConsoleLogOnBuildWebpackPlugin {
  3. apply(compiler) {
  4. compiler.hooks.run.tap(pluginName, (compilation) => {
  5. console.log('The webpack build process is starting!!!');
  6. });
  7. }
  8. }
  9. module.exports = ConsoleLogOnBuildWebpackPlugin;

二、用法

一旦 plugins 能够携带参数,你必须在 webpack 的 plugins 属性中 new 一个实例

使用 plugins 的方式有多种

  • Configuration
  • Node API

1. Configuration

  1. const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
  2. const webpack = require('webpack'); //to access built-in plugins
  3. const path = require('path');
  4. module.exports = {
  5. entry: './path/to/my/entry/file.js',
  6. output: {
  7. filename: 'my-first-webpack.bundle.js',
  8. path: path.resolve(__dirname, 'dist'),
  9. },
  10. module: {
  11. rules: [
  12. {
  13. test: /\.(js|jsx)$/,
  14. use: 'babel-loader',
  15. },
  16. ],
  17. },
  18. plugins: [
  19. new webpack.ProgressPlugin(),
  20. new HtmlWebpackPlugin({ template: './src/index.html' }),
  21. ],
  22. };
  • ProgressPlugin 用于自定义在编译期间如何报告进度
  • HtmkWebpackPlugin 将生成一个 HTML 文件,并有个 script 标签指向 my-first-webpack.bundle.js

2. Node API

当使用 Node API 时,将把 plugins 传递给配置中的 plugins 属性

  1. const webpack = require('webpack'); //to access webpack runtime
  2. const configuration = require('./webpack.config.js');
  3. let compiler = webpack(configuration);
  4. new webpack.ProgressPlugin().apply(compiler);
  5. compiler.run(function (err, stats) {
  6. // ...
  7. });

「@浪里淘沙的小法师」