The workflow of compilation
Compilation Workflow
Webpack's Compilation workflow is one of its core mechanisms, responsible for transforming the module dependency graph into the final executable code. The entire process involves multiple stages, including initialization, building, optimization, and generating output files.
Initialization Phase
When Webpack starts, it creates a Compilation
instance, which persists throughout the entire build process. The initialization phase primarily performs the following operations:
class Compilation {
constructor(compiler) {
this.hooks = {
buildModule: new SyncHook(['module']),
succeedModule: new SyncHook(['module']),
// ...other hooks
};
this.modules = new Set();
this.chunks = new Set();
}
}
Environment parameters and basic configurations are determined during this phase, including:
- Resolving the
entry
configuration - Initializing factory classes like
NormalModuleFactory
- Registering base hooks for built-in plugins
Building Phase
Entry Resolution
Starting from the configured entry, the module dependency graph is constructed:
// webpack/lib/Compilation.js
addEntry(context, entry, name, callback) {
this._addModuleChain(context, entry, (err, module) => {
// Process the entry module
});
}
Module Loading
The loader
system is used to handle different resource types:
// Example loader chain configuration
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/
}
]
}
Each module undergoes:
- Path resolution (resolve)
- Loading raw content
- Loader transformation
- AST parsing
Dependency Collection
Dependencies are analyzed using acorn
to generate the AST:
// Simplified dependency analysis process
const dependencies = [];
traverse(ast, {
ImportDeclaration(path) {
dependencies.push(path.node.source.value);
}
});
Optimization Phase
Module Merging
Optimization plugins like SplitChunksPlugin
begin their work:
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000
}
}
Tree Shaking
Static analysis based on ES Modules removes dead code:
// Original code
export function used() {...}
export function unused() {...}
// Only used() will be included in the output
Code Generation
Transforms optimized modules into executable code:
// webpack/lib/Template.js
generate() {
return {
sources: new RawSource(code),
runtimeRequirements: new Set()
};
}
Output Phase
Asset Generation
Generates final files based on the output
configuration:
// Output configuration example
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
}
File Writing
Writes to the file system via the compiler.outputFileSystem
interface:
// webpack/lib/Compiler.js
emitAssets(compilation, callback) {
const outputFiles = {};
// Generate file content...
this.outputFileSystem.writeFile(
targetPath,
content,
callback
);
}
Advanced Processing Workflow
Hot Module Replacement
Special compilation workflow in development environments:
// Hot update handling in webpack-dev-server
compiler.hooks.done.tap('HotModuleReplacement', stats => {
server.sendMessage(clients, 'hash', stats.hash);
});
Persistent Caching
Uses cache
configuration to speed up subsequent builds:
// Cache configuration example
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
Custom Processing
Extends the compilation workflow via plugins:
class MyPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('MyPlugin', compilation => {
compilation.hooks.optimize.tap('MyPlugin', () => {
// Custom optimization logic
});
});
}
}
Performance Optimization Strategies
Parallel Processing
Uses thread-loader
to accelerate builds:
{
loader: 'thread-loader',
options: {
workers: require('os').cpus().length - 1
}
}
Incremental Compilation
Leverages watch
mode to recompile only changed modules:
webpack --watch
Module Federation
Shares compilation results across projects:
// Module Federation configuration
new ModuleFederationPlugin({
name: 'app1',
exposes: {
'./Button': './src/Button.js'
}
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Compiler核心类解析