webpack插件分析

285 阅读1分钟
{
	main: {
  	import: ['./index.js']
  }
}

EntryOptionPlugin.applyEntryOption里面

	static applyEntryOption(compiler, context, entry) {
		if (typeof entry === "function") {
			const DynamicEntryPlugin = require("./DynamicEntryPlugin");
			new DynamicEntryPlugin(context, entry).apply(compiler);
		} else {
			const EntryPlugin = require("./EntryPlugin");
			for (const name of Object.keys(entry)) {
				const desc = entry[name];
				const options = EntryOptionPlugin.entryDescriptionToOptions(
					compiler,
					name,
					desc
				);
				for (const entry of desc.import) {
					new EntryPlugin(context, entry, options).apply(compiler);
				}
			}
		}
	}

第15行,EntryPlugin的context参数是项目目录:/Users/didi/webpack-study

entry参数是字符串格式的入口文件地址:./src/index.js

EntryPlugin.apply:

	apply(compiler) {
		compiler.hooks.compilation.tap(
			"EntryPlugin",
			(compilation, { normalModuleFactory }) => {
				compilation.dependencyFactories.set(
					EntryDependency,
					normalModuleFactory
				);
			}
		);

		const { entry, options, context } = this;
		const dep = EntryPlugin.createDependency(entry, options);

		compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => {
			compilation.addEntry(context, dep, options, err => {
				callback(err);
			});
		});
	}

接下来重点看compiler.hooks.make的发布:

this.hooks.make.callAsync(compilation 

这行执行时,上面EntryPlugin.apply订阅的方法(16-18行)就会执行:

			compilation.addEntry(context, dep, options, err => {
				callback(err);
			});

_addEntryItem中的name是'main'(下面代码的11行)

		if (entryData === undefined) {
			entryData = {
				dependencies: [],
				includeDependencies: [],
				options: {
					name: undefined,
					...options
				}
			};
			entryData[target].push(entry);
			this.entries.set(name, entryData);