Webpack is a static module bundler for modern JavaScript applications.

  • 实质:“前端模块打包器”

    webpack 整体是一个插件架构,所有的功能都以插件的方式集成在构建流程中,通过发布订阅事件来触发各个插件执行。webpack 核心使用 Tapable 来实现插件(plugins)的 binding(绑定)和 applying(应用)。

插件(Plugin)

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

  • 依靠插件机制实现了第三方介入编译构建的过程

    实现插件机制的大体方式

  • 「创建」—— webpack 在其内部对象上创建各种钩子;

  • 「注册」—— 插件将自己的方法注册到对应钩子上,交给 webpack ;
  • 「调用」—— webpack 编译过程中,会适时地触发相应钩子,因此也就触发了插件的方法。

    创建一个插件

  • A named JavaScript function or a JavaScript class,用于承接这个插件模块的所有逻辑;

  • Defines apply method in its prototype,会在安装插件时被调用,并被 webpack compiler 调用一次
  • Specifies an event hook to tap into,用于特定时机处理额外的逻辑
  • Manipulates webpack internal instance specific data.
  • Invokes webpack provided callback after functionality is complete.

    1. // A JavaScript class.
    2. class MyExampleWebpackPlugin {
    3. // Define `apply` as its prototype method which is supplied with compiler as its argument
    4. apply(compiler) {
    5. // Specify the event hook to attach to
    6. compiler.hooks.emit.tapAsync(
    7. 'MyExampleWebpackPlugin',
    8. (compilation, callback) => {
    9. console.log('This is an example plugin!');
    10. console.log('Here’s the `compilation` object which represents a single build of assets:', compilation);
    11. // Manipulate the build using the plugin API provided by webpack
    12. compilation.addModule(/* ... */);
    13. callback();
    14. }
    15. );
    16. }
    17. }

资料

  1. webpack之plugin内部运行机制