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.
// A JavaScript class.
class MyExampleWebpackPlugin {
// Define `apply` as its prototype method which is supplied with compiler as its argument
apply(compiler) {
// Specify the event hook to attach to
compiler.hooks.emit.tapAsync(
'MyExampleWebpackPlugin',
(compilation, callback) => {
console.log('This is an example plugin!');
console.log('Here’s the `compilation` object which represents a single build of assets:', compilation);
// Manipulate the build using the plugin API provided by webpack
compilation.addModule(/* ... */);
callback();
}
);
}
}