webpack5 plugins

作用

  • 比起loader处理确定类型的文件,plugins具有更广阔的作用,比如bundle优化、资源管理、注入环境变量等。
  • 相较于同种loader一般只添加一次,plugins可以多次添加相同插件根据不同目的。

基本定义

  • 插件是一个具有 apply 方法的类,apply方法会被 webpack compiler 调用,并且在整个编译生命周期都可以访问 compiler 对象
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

class ConsoleLogOnBuildWebpackPlugin {
  apply(compiler) {
    compiler.hooks.run.tap(pluginName, (compilation) => {
      console.log('webpack 构建正在启动!');
    });
  }
}

module.exports = ConsoleLogOnBuildWebpackPlugin;

基本使用

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack'); // 访问内置的插件
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' }),
  ],
};

  • 通过函数化的方式调用插件
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) {
  // ...
});

你可能感兴趣的:(webapck,webpack,javascript,前端)