Webpack operates within a Node.js anvironment. For local development setups, it is standard practice to install the core bundler and its command-line interface as development dependencies.
npm install --save-dev webpack webpack-cli
Project Initialization
Initialize the project to generate a package.json file. This file manages project metadata and scripts.
npm init -y
Configure the build scripts in package.json to streamline the execution process.
"scripts": {
"bundle": "webpack --config webpack.config.js"
}
Configuration File Setup
Create a webpack.config.js file in the root directory. This file exports the configuration object that defines the build behavior.
const path = require('node:path');
const settings = {
entry: './source/main.js',
output: {
fileName: 'application.js',
targetPath: path.resolve(__dirname, 'public/dist')
}
};
module.exports = settings;
Running npm run bundle will trigger the build process. It is important to note that Webpack constructs a dependency graph starting from the entry point. Only modules explicitly included in this graph are packaged. Consequently, the categorization of packages in package.json (as dependencies or devDependencies) does not impact the build output, though maintaining proper organization is recommended.
Core Configuration Concepts
1. Entry Point
The entry property indicates the initial module Webpack uses to begin building the dependency graph.
module.exports = {
entry: './client/app.js'
};
2. Output
The output property instructs Webpack on where to emit the resulting bundles and how to name the files.
const path = require('node:path');
module.exports = {
output: {
path: path.resolve(__dirname, 'build'),
filename: 'scripts/[name].js'
}
};
3. Loaders
Loaders allow Webpack to process non-JavaScript files. They transform these files into modules that become part of the dependency graph.
module.exports = {
module: {
rules: [
{
// Identify files using a regex pattern
test: /\.md$/,
// Apply the specific loader
use: 'raw-loader'
}
]
}
};
4. Plugins
Plugins extend Webpack's functionality to perform tasks such as asset management, environment variable injection, and bundle optimization.
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
})
]
};
5. Mode
Setting the mode parameter enables built-in optimizations corresponding to the environment.
module.exports = {
mode: 'production'
// 'production' enables minification; 'development' enables comments and hints
};
6. Resolution Options
Configure how Webpack resolves module imports, including file extensions and path aliases.
const path = require('node:path');
module.exports = {
resolve: {
extensions: ['.ts', '.js', '.json'], // Allows omission of extensions in imports
alias: {
'@components': path.resolve(__dirname, 'src/components/')
}
}
};
Dynamic Module Imports
Webpack provides a context feature to automatically import multiple modules from a directory based on a regular expression.
// Arguments: (directory, recursiveFlag, regExp)
const moduleContext = require.context('./modules', true, /\.js$/);
moduleContext.keys().forEach(filePath => {
const loadedModule = moduleContext(filePath);
console.log(loadedModule);
});