webpack4 大纲概论-plugins(五)

https://v4.webpack.js.org/concepts/plugins/
plugins
插件是webpack的骨架部分,可以执行加载器无法执行的其他操作
剖析:
是一个js对象有 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!!!');
    });
  }
}
module.exports = ConsoleLogOnBuildWebpackPlugin;

使用:
插件可以接受参数/选项,需要传递一个新实例给插件在 webpack.config.js中
方法一:webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
module.exports = {
  plugins: [
    new webpack.ProgressPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

方法二:Node API
也可以通过插件的方式使用 Node API
some-node-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 @ 2022-09-01 17:37  jqynr  阅读(17)  评论(0)    收藏  举报