对webpack的初步研究6

Plugins

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

它们也是这样做的目的别的,一个装载机无法做到的。

Anatomy

webpack 插件是一个具有apply方法的JavaScript对象apply方法由webpack编译器调用,可以访问整个编译生命周期。

ConsoleLogOnBuildWebpackPlugin.js

const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

class ConsoleLogOnBuildWebpackPlugin {
  apply(compiler) {
    compiler.hooks.run.tap(pluginName, compilation => {
      console.log('The webpack build process is starting!!!');
    });
  }
}

编译器钩子的tap方法的第一个参数应该是插件名称的驼峰版本。建议使用常量,以便它可以在所有钩子中重复使用。

用法 

由于插件可以使用参数/选项,因此必须将new实例传递给pluginswebpack配置中属性。

根据您使用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');

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'})
  ]
};

节点API 

使用Node API时,您还可以通过plugins配置中属性传递插件

一些节点-的script.js

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) {
  // ...
});

 

posted @ 2018-09-19 10:45  又回到了起点  阅读(145)  评论(0编辑  收藏  举报