运行时机
- 创建compiler后
- 创建compilation后
- 在compiler.hook.make钩子函数执行时创建NormalModuleFactory实例 ```javascript /* webpack.js / const createCompiler = rawOptions => { // … const compiler = new Compiler(options.context, options); // … // 设置webpack默认的配置 new WebpackOptionsApply().process(options, compiler); // … };
/* WebpackOptionsApply / class WebpackOptionsApply extends OptionsApply { // … process(options, compiler) { //… // 处理webpack入口的类 new EntryOptionPlugin().apply(compiler); //… } // … };
/* EntryOptionPlugin / class EntryoptionPlugin { // … apply(compiler) { // 注意这里在hooks.entryOption上挂载了一个钩子函数 // 当触发entryOption时,便开始运行 compiler.hooks.entryOption.tap(“EntryOptionPlugin”, (context, entry) => { EntryOptionPlugin.applyEntryOption(compiler, context, entry); return true; }); } static applyEntryOption(compiler, context, entry) { if (typeof entry === “function”) { // 函数入口处理… } else { const EntryPlugin = require(“./EntryPlugin”); for (const name of Object.keys(entry)) { // …入口参数处理 for (const entry of desc.import) { // 入口插件 new EntryPlugin(context, entry, options).apply(compiler); } } } } };
/* EntryPlugin /
class EntryPlugin {
apply(compiler) {
// compilation创建完成后的钩子函数
compiler.hooks.compilation.tap(
“EntryPlugin”,
(compilation, { normalModuleFactory }) => {
// 将normalModuleFactory注册进依赖
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
// …
// compilation结束之前注册进函数
compiler.hooks.make.tapAsync(“EntryPlugin”, (compilation, callback) => {
// 运行NormalModuleFactory.create函数,创建NormalModule
compilation.addEntry(context, dep, options, err => {
callback(err);
});
});
}
}
```
