非常教程

Webpack参考手册

概念 | Concepts

插件 | Plugins

插件是webpack 的支柱。webpack本身是建立在您在webpack配置中使用的相同插件系统上的!

插件目的在于解决 loader 无法实现的其他事

剖析

webpack 插件是一个具有 apply 属性的 JavaScript 对象。apply 属性会被 webpack compiler 调用,并且 compiler 对象可在整个编译生命周期访问。

ConsoleLogOnBuildWebpackPlugin.js

function ConsoleLogOnBuildWebpackPlugin() {

};

ConsoleLogOnBuildWebpackPlugin.prototype.apply = function(compiler) {
  compiler.plugin('run', function(compiler, callback) {
    console.log("The webpack build process is starting!!!");

    callback();
  });
};

作为一个聪明的JavaScript开发人员,您可能还记得这个Function.prototype.apply方法。由于这种方法,你可以将任何函数作为插件传递(this将指向compiler)。您可以使用此样式在配置中内联自定义插件。

用法

由于插件可以携带参数/选项,你必须在 webpack 配置中,向 plugins 属性传入 new 实例。

根据你的 webpack 用法,这里有多种方式使用插件。

配置

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
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

即便使用 Node API,用户也应该在配置中传入 plugins 属性。compiler.apply 并不是推荐的使用方式。

some-node-script.js

  const webpack = require('webpack'); //to access webpack runtime
  const configuration = require('./webpack.config.js');

  let compiler = webpack(configuration);
  compiler.apply(new webpack.ProgressPlugin());

  compiler.run(function(err, stats) {
    // ...
  });

你知道吗:上面看到的例子与webpack运行时本身非常相似!隐藏在webpack源代码中的很多很好的用法示例可以应用到您自己的配置和脚本中!

Webpack

webpack 是一个模块打包器。webpack 处理带有依赖关系的模块,生成一系列表示这些模块的静态资源。

主页 https://webpack.js.org/
源码 https://github.com/webpack/webpack
发布版本 3.8.1

Webpack目录

1.指南 | Guides
2.接口 | API
3.概念 | Concepts
4.组态 | Configuration
5.装载 | Loaders