# webpack源码 入口
:)
let's go to figure out what happen when you run [npm build]~
- 看源码记得
yarn install
一下
# 大致运行流程
- PS:
=
是双向的 new Webpack
class Compiler
-createCompiler()
=enviroment
compiler.compiler
=beforeRun to plugin
-hook:make
class Compilation
-compilation.addEntry
=loader-runner
-loader a b c
compilation.seal
- back to
compiler.emitAssets
# webpack.js
- 入口在 /lib/webpack.js
const createMultiCompiler = (childOptions, options) =>{...}
const createCompiler = rawOptions => {
..
const compiler = new Compiler(options.context);
compiler.options = options;
...apply(compiler);
...
compiler.hooks.environment.call();
compiler.hooks.afterEnvironment.call();
new WebpackOptionsApply().process(options, compiler);
compiler.hooks.initialize.call();
return compiler;
}
const webpack =(
(options, callback) => {..}
)
module.exports = webpack;
# const webpack
const webpack =(
(options, callback) => {
const create = () => {
if (!webpackOptionsSchemaCheck(options)) {
getValidateSchema()(webpackOptionsSchema, options);//校验
}
let compiler;
let watch = false;
let watchOptions;
...
{
const webpackOptions = (options);
compiler = createCompiler(webpackOptions);
//applyWebpackOptionsBaseDefaults 里面有
watch = webpackOptions.watch;
watchOptions = webpackOptions.watchOptions || {};
}
return { compiler, watch, watchOptions }; // 最终配置
};
if (callback) {
try {
const { compiler, watch, watchOptions } = create(); //创建对象
if (watch) {
compiler.watch(watchOptions, callback);
} else {
compiler.run((err, stats) => {
..
});
}
...
} else {
const { compiler, watch } = create();
if (watch) {
...
}
return compiler;
}
}
);
# getValidateSchema
- 校验用
# createCompiler`
const createCompiler = rawOptions => {
const options = getNormalizedWebpackOptions(rawOptions);
applyWebpackOptionsBaseDefaults(options); // 合并选项
const compiler = new Compiler(options.context);
compiler.options = options;
new NodeEnvironmentPlugin({
infrastructureLogging: options.infrastructureLogging
}).apply(compiler);
if (Array.isArray(options.plugins)) { //遍历注入plugin
for (const plugin of options.plugins) {
if (typeof plugin === "function") {
plugin.call(compiler, compiler);
} else {
plugin.apply(compiler);
}
}
}
applyWebpackOptionsDefaults(options);
compiler.hooks.environment.call();
compiler.hooks.afterEnvironment.call();
new WebpackOptionsApply().process(options, compiler); // 加载各种内置插件
compiler.hooks.initialize.call();
return compiler;
};
# WebpackOptionsApply
- in lib/config/default.js
- 相关插件会监听compiler.make钩子