Webpack functions as a static module bundler that processes modern applications by analyzing their dependency networks. When invoked, it recursively traverses the project, constructing a comprehensive graph where every import statement becomes a tracked node. This process ensures that all required assets are correctly compiled and optimized for deployment.
Configuration directives are typically centralized in a dedicated JavaScript file, conventionally named build.config.js. The compilation pipeline relies on four foundational pillars to orchestrate asset processing.
- Entry Points
The entry configuration defines the initial module(s) from which the bundler begins constructing its internal dependency map. While a single string is sufficient for basic projects, the property also accepts an object to handle multi-page applications or separate vendor bundles.
const projectSettings = {};
projectSettings.entry = {
application: './src/main.ts',
legacy: './src/polyfills.js'
};
module.exports = projectSettings;
- Output Configuration
This directive specifies the destination directory for generated bundles and dictates their naming conventions. By default, assets are written to a ./dist folder, but this can be customized to match deployment requirements.
const pathResolver = require('path');
const buildOptions = {
entry: './src/main.ts',
output: {
path: pathResolver.join(process.cwd(), 'public/assets'),
filename: 'bundle.[contenthash:8].js'
}
};
module.exports = buildOptions;
- Loaders
By default, the bundler natively understands only JavaScript and JSON files. Loaders bridge this gap by transforming non-JS assets (such as stylesheets, images, or TypeScript) in to valid modules that can be added to the dependency graph. Configuration relies on a rules array within the module object, where test matches specific file extensions and use applies the appropriate transformation pipeline.
const pathResolver = require('path');
const transformerConfig = {
module: {
rules: [
{
test: /\.(css|scss)$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { modules: true } },
'sass-loader'
]
}
]
}
};
module.exports = transformerConfig;
- Plugins
While loaders handle individual file transformations, plugins operate on the broader compilation lifecycle. They provide powerful hooks for tasks ranging from bundle optimization and environment variable injection to generating HTML files and cleaning previous build artifacts. To integrate a plugin, instantiate it with the new keyword and append it to the plugins array.
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlTemplate = require('html-webpack-plugin');
const extensionConfig = {
plugins: [
new CleanWebpackPlugin(),
new HtmlTemplate({
template: './public/base.html',
inject: 'body'
})
]
};
module.exports = extensionConfig;