Webpack翻译之Plugin

175 阅读2分钟

Plugins

Plugins are the backbone of webpack. webpack itself is built on the same plugin system that you use in your webpack configuration!

Plugins是webpack的骨干,webpack自身是建立在与webpack配置相同的插件系统中.

They also serve the purpose of doing anything else that a loader cannot do.

他们也提供做一些loader不能做的事情的目的。

Anatomy

A webpack plugin is a JavaScript object that has an apply method. This apply method is called by the webpack compiler, giving access to the entire compilation lifecycle.

webpack插件一个有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;

The first parameter of the tap method of the compiler hook should be a camelized version of the plugin name. It is advisable to use a constant for this so it can be reused in all hooks.

编译勾子第一个参数应该是驼峰结构的插件名称,它是建议使用常量,以便整个勾子能够重用;

Usage

Since plugins can take arguments/options, you must pass a new instance to the plugins property in your webpack configuration.

如果插件可以带参数/配置,你必须在webpack配置中给插件传入一个新的对象.

Depending on how you are using webpack, there are multiple ways to use plugins.

根据你如何使用webpack,这里有几种使用插件的方法

Configuration

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

Node API

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

let compiler = webpack(configuration);

new webpack.ProgressPlugin().apply(compiler);

compiler.run(function(err, stats) {
  // ...
});
Did you know: The example seen above is extremely similar to the webpack runtime itself! There are lots of great usage examples hiding in the webpack source code that you can apply to your own configurations and scripts!
你知道吗: 看上面的例子是非常像webpack执行自己。这里有还不是的可以使用的例子隐藏在webpack源码中,你可以运行你自己的配置和脚本