webpack5 基本概念 —— 插件(plugin)

插件 是 webpack 的 支柱 功能。

Webpack 自身也是构建于在 webpack 配置中用到的 相同的插件系统 之上!

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

如果在插件中使用了 webpack-sources 的 package,请使用 require('webpack').sources 替代 require('webpack-sources'),以避免持久缓存的版本冲突。

webpack 插件是一个具有 apply方法的 JavaScript 对象。

apply 方法会被 webpack compiler 调用,并且在 整个 编译生命周期都可以访问 compiler 对象。

ConsoleLogOnBuildWebpackPlugin.js

const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

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

module.exports = ConsoleLogOnBuildWebpackPlugin;

compiler hook 的 tap 方法的第一个参数,应该是驼峰式命名的插件名称。

建议为此使用一个常量,以便它可以在所有 hook 中重复使用。

用法

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

配置方式

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack'); // 访问内置的插件
const path = require('path');

module.exports = {
  entry: './path/my/entry/file.js',
  output: {
    filename: 'my-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' })
  ]
};

ProgressPlugin 用于自定义编译过程中的进度报告,HtmlWebpackPlugin 将生成一个 HTML 文件,并在其中使用 script 引入一个名为 my-webpack.bundle.js 的 JS 文件。

Node API 方式

在使用 Node API 时,还可以通过配置中的 plugins 属性传入插件。

some-node-script.js

const webpack = require('webpack'); // 访问 webpack 运行时(runtime)
const configuration = require('./webpack.config.js');

let compiler = webpack(configuration);

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

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

项目实践

内置的 BannerPlugin 插件,用于在文件头部输出一些注释信息。

webpack.config.js 文件:


const path = require('path')
var webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: "./src/index.js",
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
  },
  plugins: [
    new webpack.BannerPlugin('这是添加的 webpack 实例注释')
  ]
};

index.js:

if (process.env.NODE_ENV !== 'production') {
  console.log('Current we are in development mode!');
}

function component () {
  const element = document.createElement('pre');

  element.innerHTML = [
    'Hello webpack!',
    '5 cubed is equal to ' ].join('\n\n');

  return element;
}

document.body.appendChild(component());

运行npm run build
webpack5 基本概念 —— 插件(plugin)_第1张图片

可以看到,生成了main.bundle.js文件。

打开main.bundle.js:

/*! 这是添加的 webpack 实例注释 */
/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "./src/index.js":
/*!**********************!*\
  !*** ./src/index.js ***!
  \**********************/
/***/ (() => {

eval("if (true) {\r\n  console.log('Current we are in development mode!');\r\n}\r\n\r\nfunction component () {\r\n  const element = document.createElement('pre');\r\n\r\n  element.innerHTML = [\r\n    'Hello webpack!',\r\n    '5 cubed is equal to ' ].join('\\n\\n');\r\n\r\n  return element;\r\n}\r\n\r\ndocument.body.appendChild(component());\n\n//# sourceURL=webpack://webpack-demo/./src/index.js?");

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module can't be inlined because the eval devtool is used.
/******/ 	var __webpack_exports__ = {};
/******/ 	__webpack_modules__["./src/index.js"]();
/******/ 	
/******/ })()
;

可以看到,文件头部出现了指添加的注释信息。

你可能感兴趣的:(webpack,webpack)