Okay, here’s a comprehensive article on getting started with Webpack, aiming for approximately 5000 words:
Getting Started with Webpack: A Practical Guide
Webpack has become an indispensable tool in modern web development. It’s a powerful module bundler that takes your application’s code, assets (like images, fonts, and CSS), and dependencies, and transforms them into optimized bundles that browsers can load efficiently. This guide provides a deep dive into Webpack, covering everything from basic concepts to advanced configurations. We’ll build a practical project step-by-step, explaining each decision along the way.
Table of Contents
-
Why Webpack? Understanding the Need for Module Bundlers
- The Problems of Traditional Web Development
- The Rise of JavaScript Modules (ES Modules)
- The Benefits of Bundling
- Webpack vs. Other Bundlers (Parcel, Rollup, Browserify)
-
Setting Up Your Development Environment
- Installing Node.js and npm
- Creating a Project Directory
- Initializing a
package.json
File
-
Your First Webpack Configuration: A Minimal Example
- Creating Source Files (
index.js
,message.js
) - Installing Webpack and Webpack CLI
- Creating
webpack.config.js
- The
entry
Point - The
output
Configuration - Running Webpack
- Creating an
index.html
File - Understanding the Bundled Output
- Creating Source Files (
-
Loaders: Handling Different File Types
- What are Loaders?
- Using
style-loader
andcss-loader
for CSS - Installing the Loaders
- Configuring Loaders in
webpack.config.js
- Adding CSS to Your Project
- Using
file-loader
andurl-loader
for Images- Handling different image size
- Using Babel for JavaScript Transpilation
- Installing Babel and Presets
- Configuring Babel in
webpack.config.js
- Other Common Loaders (Sass, Less, TypeScript)
-
Plugins: Extending Webpack’s Capabilities
- What are Plugins?
- Using
HtmlWebpackPlugin
to Generate HTML- Installing the Plugin
- Configuring the Plugin in
webpack.config.js
- Customizing the HTML Template
- Using
CleanWebpackPlugin
to Clean the Output Directory- Installing the Plugin
- Configuring the Plugin in
webpack.config.js
- Using
MiniCssExtractPlugin
to Extract CSS into Separate Files- Installing the Plugin
- Configuring the Plugin in
webpack.config.js
- Difference to
style-loader
- Other Useful Plugins (CopyWebpackPlugin, DefinePlugin)
-
Webpack Dev Server: Streamlining Development
- What is Webpack Dev Server?
- Installing
webpack-dev-server
- Configuring the Dev Server in
webpack.config.js
- Using the
devServer
Options (port, contentBase, hot) - Hot Module Replacement (HMR)
- Setting Up a Development Script in
package.json
-
Code Splitting: Optimizing for Performance
- Why Code Splitting?
- Entry Point Splitting
- Dynamic Imports (using
import()
) - Configuring
optimization.splitChunks
- Lazy Loading Modules
-
Production Builds: Preparing for Deployment
- Creating Separate Configurations for Development and Production
- Using
webpack-merge
to Manage Configurations - Setting
mode
to ‘production’ - Minification and Optimization (TerserPlugin, CssMinimizerPlugin)
- Source Maps for Debugging
- Environment Variables (using
DefinePlugin
)
-
Advanced Topics
- Caching and Long-Term Caching
- Tree Shaking
- Module Federation
- Working with TypeScript
- Using Webpack with Frameworks (React, Vue, Angular)
-
Troubleshooting Common Issues
- Debugging Webpack Configurations
- Handling Module Resolution Errors
- Dealing with Loader and Plugin Errors
- Performance Optimization Tips
-
Conclusion and Further Resources
1. Why Webpack? Understanding the Need for Module Bundlers
Before diving into Webpack, it’s crucial to understand why it exists and the problems it solves.
The Problems of Traditional Web Development
In the early days of web development, managing JavaScript code was relatively simple. You’d typically include multiple <script>
tags in your HTML, each loading a separate JavaScript file. However, this approach has several significant drawbacks:
- Global Scope Pollution: All variables and functions declared in these separate files end up in the global scope. This can lead to naming conflicts, accidental overwrites, and generally messy code.
- Dependency Management Hell: You have to manually ensure that your script files are loaded in the correct order, based on their dependencies. This becomes increasingly complex as your project grows.
- Performance Issues: Loading many small files results in numerous HTTP requests, which can significantly slow down page load times. Browsers have limits on the number of concurrent requests they can make.
- Difficulties with Modern JavaScript Features: Older browsers might not support newer JavaScript features (like ES6 modules, classes, arrow functions, etc.).
The Rise of JavaScript Modules (ES Modules)
To address these issues, the JavaScript community developed the concept of modules. Modules allow you to organize your code into self-contained units, with their own scope. ES Modules (ESM) are the standardized module system built into modern JavaScript. They use the import
and export
keywords to define dependencies and expose functionality.
“`javascript
// message.js (a module)
export const greeting = “Hello, world!”;
// index.js (importing the module)
import { greeting } from ‘./message.js’;
console.log(greeting);
“`
While ES Modules are a huge improvement, they still present a challenge in the browser:
- Browser Support: While most modern browsers support ES Modules, older browsers (like Internet Explorer) do not.
- HTTP Requests: Even with ES Modules, each
import
statement can still result in a separate HTTP request, impacting performance.
The Benefits of Bundling
This is where module bundlers like Webpack come in. A module bundler takes your code, including all its dependencies (even those written as ES Modules), and combines them into one or more bundles. These bundles are optimized JavaScript files that can be loaded efficiently by the browser. The benefits of bundling include:
- Dependency Resolution: Webpack automatically resolves all dependencies between your modules, ensuring they are included in the correct order.
- Code Transformation: Webpack can transform your code using loaders, allowing you to use modern JavaScript features (like ES6+) and transpile them into code compatible with older browsers. It can also handle CSS, images, and other assets.
- Performance Optimization: Webpack can minify and optimize your code, reducing file sizes and improving load times. Techniques like code splitting allow you to further optimize by loading only the code needed for a specific page or feature.
- Improved Developer Experience: Webpack simplifies the development workflow by handling many complex tasks automatically. Features like Hot Module Replacement (HMR) allow for instant updates in the browser without full page reloads.
Webpack vs. Other Bundlers (Parcel, Rollup, Browserify)
While Webpack is a popular choice, other bundlers exist. Here’s a brief comparison:
- Parcel: Known for its “zero-configuration” approach. It automatically detects dependencies and handles many common tasks without requiring explicit configuration. Good for smaller projects or quick prototyping.
- Rollup: Focuses on creating highly optimized bundles for libraries and modules, particularly those using ES Modules. Excellent for tree shaking (removing unused code).
- Browserify: One of the earliest module bundlers, primarily focused on bundling Node.js-style
require()
modules for use in the browser. Less common now that Webpack and others offer more comprehensive features.
Webpack is generally favored for larger, more complex applications due to its flexibility, extensive plugin ecosystem, and robust community support. It offers fine-grained control over the bundling process, allowing for highly customized configurations.
2. Setting Up Your Development Environment
Before you can use Webpack, you need to set up your development environment. This involves installing Node.js and npm.
Installing Node.js and npm
Webpack is a JavaScript tool and runs on Node.js. npm (Node Package Manager) is the standard package manager for Node.js and is used to install Webpack and its related tools.
- Download Node.js: Go to the official Node.js website (https://nodejs.org/) and download the LTS (Long-Term Support) version for your operating system. The LTS version is generally recommended for stability.
- Install Node.js: Run the downloaded installer and follow the on-screen instructions. This will install both Node.js and npm.
-
Verify Installation: Open your terminal (or command prompt on Windows) and run the following commands:
bash
node -v
npm -vThese commands should display the installed versions of Node.js and npm, respectively. If you see version numbers, the installation was successful.
Creating a Project Directory
Create a new directory for your project. This is where you’ll store all your code and configuration files. You can name it anything you like (e.g., webpack-demo
).
bash
mkdir webpack-demo
cd webpack-demo
Initializing a package.json
File
The package.json
file is a crucial part of any Node.js project. It contains metadata about your project, including its name, version, dependencies, and scripts.
To create a package.json
file, run the following command in your project directory:
bash
npm init -y
The -y
flag automatically accepts the default settings, creating a basic package.json
file. You can open this file in a text editor and modify it later if needed.
3. Your First Webpack Configuration: A Minimal Example
Let’s start with a simple example to understand the core concepts of Webpack.
Creating Source Files (index.js
, message.js
)
Create two JavaScript files in your project directory:
-
src/message.js
:javascript
// src/message.js
export const greeting = "Hello from Webpack!"; -
src/index.js
:“`javascript
// src/index.js
import { greeting } from ‘./message.js’;console.log(greeting);
``
src` folder in advance.
Create the
Installing Webpack and Webpack CLI
You need to install Webpack and its command-line interface (Webpack CLI) as development dependencies:
bash
npm install --save-dev webpack webpack-cli
--save-dev
(or -D
) is used, because it is only needed for local development and building, not in the production environment.
Creating webpack.config.js
This is the heart of your Webpack setup. Create a file named webpack.config.js
in the root of your project directory. This file will contain the configuration for Webpack.
“`javascript
// webpack.config.js
const path = require(‘path’);
module.exports = {
entry: ‘./src/index.js’,
output: {
filename: ‘bundle.js’,
path: path.resolve(__dirname, ‘dist’),
},
};
“`
The entry
Point
The entry
property tells Webpack where to start bundling your code. In this case, it’s set to ./src/index.js
. Webpack will follow the import
statements from this file to find all the dependencies.
The output
Configuration
The output
property tells Webpack where to save the bundled output and how to name it.
filename
: Specifies the name of the output file (e.g.,bundle.js
).path
: Specifies the directory where the output file should be saved. We usepath.resolve(__dirname, 'dist')
to create an absolute path to adist
directory within your project.__dirname
is a Node.js global variable that represents the current directory.
Running Webpack
Now, you can run Webpack to bundle your code. In your terminal, run:
bash
npx webpack
npx
is a tool that comes with npm (version 5.2+) and allows you to run locally installed packages without having to add them to your package.json
scripts.
After running this command, you should see a new dist
directory created, containing a file named bundle.js
. This file contains the combined and processed code from index.js
and message.js
.
Creating an index.html
File
To see the bundled code in action, create an index.html
file in your project’s root directory:
“`html
“`
This HTML file includes the bundle.js
file using a <script>
tag. Open index.html
in your browser, open the browser’s developer console (usually by pressing F12), and you should see the message “Hello from Webpack!” printed to the console.
Understanding the Bundled Output
If you open dist/bundle.js
, you’ll see a lot of Webpack-generated code. This code handles module loading, dependency resolution, and other tasks. Your original code from index.js
and message.js
will be embedded within this larger structure. The important thing is that Webpack has successfully combined your code into a single file that the browser can load.
4. Loaders: Handling Different File Types
Webpack, by default, only understands JavaScript and JSON files. To handle other file types (like CSS, images, fonts, etc.), you need to use loaders. Loaders are transformations that are applied to files before they are added to the bundle.
What are Loaders?
Loaders are essentially functions that take the content of a file as input and return the transformed content. They allow you to preprocess files as they are imported into your JavaScript code.
Using style-loader
and css-loader
for CSS
Let’s add CSS to our project. We’ll use two loaders:
css-loader
: Interprets@import
andurl()
in CSS files, resolving them likeimport/require()
in JavaScript.style-loader
: Injects the CSS into the DOM by creating<style>
tags.
Installing the Loaders
bash
npm install --save-dev style-loader css-loader
Configuring Loaders in webpack.config.js
Modify your webpack.config.js
file to include a module
section with rules for how to handle different file types:
“`javascript
// webpack.config.js
const path = require(‘path’);
module.exports = {
entry: ‘./src/index.js’,
output: {
filename: ‘bundle.js’,
path: path.resolve(__dirname, ‘dist’),
},
module: {
rules: [
{
test: /.css$/,
use: [‘style-loader’, ‘css-loader’],
},
],
},
};
“`
module.rules
: An array of rules that define how to handle different file types.test
: A regular expression that matches the file extensions you want to process (e.g.,/\.css$/
matches files ending in.css
).use
: An array of loaders to apply to the matched files. Loaders are applied from right to left (or bottom to top if written vertically). In this case,css-loader
is applied first, thenstyle-loader
.
Adding CSS to Your Project
Create a src/style.css
file:
“`css
/ src/style.css /
body {
background-color: lightblue;
font-family: sans-serif;
}
h1 {
color: navy;
}
“`
Now, import the CSS file into your src/index.js
:
“`javascript
// src/index.js
import { greeting } from ‘./message.js’;
import ‘./style.css’; // Import the CSS
console.log(greeting);
// Add a heading to the body.
const heading = document.createElement(‘h1’);
heading.textContent = greeting;
document.body.appendChild(heading);
“`
Run npx webpack
again. Now, when you open index.html
in your browser, you should see the styles from style.css
applied. The style-loader
has injected the CSS into a <style>
tag in the <head>
of your HTML.
Using file-loader
and url-loader
for Images
To handle images, you can use file-loader
or url-loader
.
file-loader
: Resolvesimport/require()
on a file into a URL and emits the file into the output directory.url-loader
: Works likefile-loader
, but can also inline small files as Base64 URIs. This can reduce HTTP requests for small images.
Handling different image size
Let’s install url-loader
(which also requires file-loader
as a peer dependency):
bash
npm install --save-dev url-loader file-loader
Update webpack.config.js
:
“`javascript
// webpack.config.js
const path = require(‘path’);
module.exports = {
entry: ‘./src/index.js’,
output: {
filename: ‘bundle.js’,
path: path.resolve(__dirname, ‘dist’),
},
module: {
rules: [
{
test: /.css$/,
use: [‘style-loader’, ‘css-loader’],
},
{
test: /.(png|jpg|gif|svg)$/,
use: [
{
loader: ‘url-loader’,
options: {
limit: 8192, // Inline files smaller than 8KB as Base64 URIs
name: ‘[name].[hash:7].[ext]’, // Customize the output file name
},
},
],
},
],
},
};
“`
test
: Matches common image file extensions.options.limit
: Sets the size limit (in bytes) for inlining files. Files smaller than this limit will be inlined as Base64 URIs. Files larger than the limit will be handled byfile-loader
(copied to the output directory).options.name
: Specifies how the output files should be named.[name]
is the original file name,[hash:7]
is a 7-character hash of the file content (for cache busting), and[ext]
is the file extension.
Now, create a src/images
directory and add an image file (e.g., webpack-logo.png
).
Import the image in src/index.js
:
“`javascript
// src/index.js
import { greeting } from ‘./message.js’;
import ‘./style.css’;
import logo from ‘./images/webpack-logo.png’; // Import the image
console.log(greeting);
const heading = document.createElement(‘h1’);
heading.textContent = greeting;
document.body.appendChild(heading);
const img = document.createElement(‘img’);
img.src = logo; // Use the imported URL
document.body.appendChild(img);
“`
Run npx webpack
. If your image is smaller than 8KB, it will be inlined directly into your JavaScript as a Base64 URI. If it’s larger, it will be copied to the dist
directory, and the logo
variable will contain the URL to that file.
Using Babel for JavaScript Transpilation
Babel is a JavaScript compiler that allows you to use the latest JavaScript features (ES6+, etc.) and transpile them into code that is compatible with older browsers.
Installing Babel and Presets
bash
npm install --save-dev @babel/core @babel/preset-env babel-loader
@babel/core
: The core Babel compiler.@babel/preset-env
: A preset that automatically determines the Babel plugins and polyfills needed based on your target browsers.babel-loader
: The Webpack loader for Babel.
Configuring Babel in webpack.config.js
Add a rule for JavaScript files to your webpack.config.js
:
“`javascript
// webpack.config.js
const path = require(‘path’);
module.exports = {
// … other configurations …
module: {
rules: [
// … other rules …
{
test: /.js$/,
exclude: /node_modules/, // Exclude node_modules from transpilation
use: {
loader: ‘babel-loader’,
options: {
presets: [‘@babel/preset-env’],
},
},
},
],
},
};
“`
test: /\.js$/
: Apply to .js fileexclude: /node_modules/
: Excludes thenode_modules
directory from transpilation. This is important because packages innode_modules
are usually already transpiled.options.presets
: Specifies the Babel presets to use.@babel/preset-env
is a smart preset that automatically includes the necessary transformations based on your target environment.
Now, you can use modern JavaScript features in your code, and Babel will transpile them into code that works in older browsers. For example, you can freely use const
, let
and arrow functions.
Other Common Loaders (Sass, Less, TypeScript)
- Sass/Less: For using Sass or Less preprocessors for CSS. You’ll need
sass-loader
(andnode-sass
orsass
) orless-loader
(andless
). - TypeScript: For using TypeScript. You need
ts-loader
.
The configuration process for these loaders is similar to the examples above. You install the loader and add a rule to webpack.config.js
specifying how to handle the corresponding file types.
5. Plugins: Extending Webpack’s Capabilities
While loaders transform individual files, plugins can perform a wider range of tasks, such as optimizing bundles, managing assets, and injecting environment variables. Plugins operate on the entire compilation process.
What are Plugins?
Plugins are JavaScript objects that have an apply
method. This method is called by the Webpack compiler, giving the plugin access to the entire compilation lifecycle.
Using HtmlWebpackPlugin
to Generate HTML
Instead of manually creating an index.html
file and including the bundled script, you can use HtmlWebpackPlugin
to automatically generate the HTML file for you.
Installing the Plugin
bash
npm install --save-dev html-webpack-plugin
Configuring the Plugin in webpack.config.js
“`javascript
// webpack.config.js
const path = require(‘path’);
const HtmlWebpackPlugin = require(‘html-webpack-plugin’);
module.exports = {
// … other configurations …
plugins: [
new HtmlWebpackPlugin({
title: ‘Webpack Demo’, // Set the title of the generated HTML
template: ‘./src/index.html’, // Use a custom template (optional)
}),
],
};
“`
plugins
: An array of plugins to use.new HtmlWebpackPlugin(...)
: Creates a new instance of theHtmlWebpackPlugin
.title
: Sets the title of the generated HTML file.template
: (Optional) Specifies a custom HTML template to use. If you don’t provide a template, a default one will be used.
Customizing the HTML Template
If you use the template
option, create a src/index.html
file (this is different from the index.html
we created earlier in the root directory):
“`html
“`
<%= htmlWebpackPlugin.options.title %>
: This is a template placeholder that will be replaced with thetitle
option you provided inwebpack.config.js
.
Now, you can remove the <script src="dist/bundle.js"></script>
line from your original index.html
file (in project root), or better remove the index.html
file in the root directory. HtmlWebpackPlugin
will automatically inject the correct script tag into the generated HTML file.
Run npx webpack
. The dist
folder will now contain an index.html
file, along with your bundle.js
and any other assets. Webpack will automatically inject the <script>
tag to include bundle.js
into the generated HTML.
Using CleanWebpackPlugin
to Clean the Output Directory
It’s good practice to clean your output directory (dist
) before each build to remove any old files. CleanWebpackPlugin
does this automatically.
Installing the Plugin
bash
npm install --save-dev clean-webpack-plugin
Configuring the Plugin in webpack.config.js
“`javascript
// webpack.config.js
const path = require(‘path’);
const HtmlWebpackPlugin = require(‘html-webpack-plugin’);
const { CleanWebpackPlugin } = require(‘clean-webpack-plugin’); // Note the destructuring
module.exports = {
// … other configurations …
plugins: [
new CleanWebpackPlugin(), // Clean the ‘dist’ directory before each build
new HtmlWebpackPlugin({
title: ‘Webpack Demo’,
template: ‘./src/index.html’,
}),
],
};
“`
Now, each time you run npx webpack
, the dist
directory will be cleaned before the new files are generated.
Using MiniCssExtractPlugin
to Extract CSS into Separate Files
Instead of style-loader, you can use MiniCssExtractPlugin
to extract CSS.
Installing the Plugin
bash
npm install --save-dev mini-css-extract-plugin
Configuring the Plugin in webpack.config.js
“`javascript
const path = require(‘path’);
const HtmlWebpackPlugin = require(‘html-webpack-plugin’);
const { CleanWebpackPlugin } = require(‘clean-webpack-plugin’);
const MiniCssExtractPlugin = require(‘mini-css-extract-plugin’);
module.exports = {
// … other configurations …
module: {
rules: [
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader, // Use MiniCssExtractPlugin.loader instead of style-loader
‘css-loader’,
],
},
// … other rules …
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: ‘Webpack Demo’,
template: ‘./src/index.html’,
}),
new MiniCssExtractPlugin({
filename: ‘[name].[contenthash].css’, // Output CSS file name
}),
],
};
“`
- Replace
style-loader
withMiniCssExtractPlugin.loader
in theuse
array for your CSS rule. - Add a new instance of
MiniCssExtractPlugin
to theplugins
array.filename
: Specifies the name of the output CSS file. We use[name].[contenthash].css
to include a content hash for cache busting.
Difference to style-loader
* style-loader
: Injects CSS into the DOM using <style>
tags. This is suitable for development because it enables Hot Module Replacement (HMR) for CSS.
* MiniCssExtractPlugin
: Extracts CSS into separate files. This is generally preferred for production because it allows for parallel loading of CSS and JavaScript, and it can be cached separately by the browser.
Other Useful Plugins (CopyWebpackPlugin, DefinePlugin)
-
CopyWebpackPlugin
: Copies individual files or entire directories to the output directory. Useful for static assets that don’t need to be processed by loaders.bash
npm install --save-dev copy-webpack-plugin
javascript
new CopyWebpackPlugin({
patterns: [
{ from: 'src/public', to: 'public' }, // Copies files from src/public to dist/public
],
}), -
DefinePlugin
: Creates global constants that can be used in your code. Useful for setting environment variables.javascript
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), // Define NODE_ENV
}),
6. Webpack Dev Server: Streamlining Development
webpack-dev-server
provides a development server that automatically recompiles your code and reloads the browser whenever you make changes. This significantly speeds up the development workflow.
What is Webpack Dev Server?
webpack-dev-server
is a small Node.js Express server that serves your bundled files. It also includes a small runtime that communicates with the browser, enabling features like Hot Module Replacement (HMR).
Installing webpack-dev-server
bash
npm install --save-dev webpack-dev-server
Configuring the Dev Server in webpack.config.js
“`javascript
// webpack.config.js
// … other imports …
module.exports = {
// … other configurations …
devServer: {
static: {
directory: path.join(__dirname, ‘dist’),
},
port: 8080, // Port to run the server on
hot: true, // Enable Hot Module Replacement (HMR)
open: true, // Automatically open the browser
},
};
“`
devServer
: An object containing the configuration forwebpack-dev-server
.static.directory
: Specifies the directory to serve static files from (usually yourdist
directory).port
: The port number to run the server on (default is 8080).hot
: Enables Hot Module Replacement (HMR). With HMR, changes to your code are automatically injected into the browser without a full page reload.open
: Whether to automatically open browser or not.
Hot Module Replacement (HMR)
HMR is a powerful feature that allows you to update modules in your application without a full page reload. This makes development much faster, as you can see the effects of your changes almost instantly. Webpack Dev Server provides built-in support for HMR.
Setting Up a Development Script in package.json
To make it easier to start the development server, add a script to your package.json
file:
json
// package.json
{
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production"
}
}
"start"
: Runswebpack serve
to start the development server. The--mode development
flag sets the Webpack mode to “development”."build"
: Runswebpack
to perform a production build, with mode set to “production”.
Now, you can start the development server by running:
bash
npm start
This will start the server, open your browser, and automatically reload the page whenever you make changes to your code. The --mode
flag influences how Webpack processes your code (e.g., enabling optimizations in production mode).
7. Code Splitting: Optimizing for Performance
Code splitting is a technique for splitting your code into multiple bundles that can be loaded on demand or in parallel. This can significantly improve the initial load time of your application, as users only need to download the code that’s required for the current page or feature.
Why Code Splitting?
- Reduced Initial Load Time: By splitting your code into smaller chunks, you reduce the amount of code that needs to be downloaded and parsed when the user first visits your site.
- Improved Caching: Browsers can cache individual bundles separately. If you update one part of your application, only the corresponding bundle needs to be re-downloaded.
- Better User Experience: Faster load times lead to a better user experience, especially on slower network connections.
Entry Point Splitting
The simplest form of code splitting is to create multiple entry points in your Webpack configuration. Each entry point will generate a separate bundle.
javascript
// webpack.config.js
module.exports = {
entry: {
main: './src/index.js',
about: './src/about.js', // Add a new entry point
},
output: {
filename: '[name].bundle.js', // Use [name] to create separate bundles
path: path.resolve(__dirname, 'dist'),
},
// ... other configurations ...
};
entry
: Now an object with multiple entry points.output.filename
: Uses[name]
as a placeholder. This will be replaced with the name of each entry point (e.g.,main.bundle.js
,about.bundle.js
).
Create a new file src/about.js
with some content. You’d then need separate HTML files (or use a templating engine) to include the appropriate bundle for each page.
Dynamic Imports (using import()
)
Dynamic imports allow you to load modules on demand, at runtime. This is a powerful way to implement lazy loading, where you only load code when it’s actually needed.
“`javascript
// src/index.js
import ‘./style.css’;
const heading = document.createElement(‘h1’);
heading.textContent = “Click the button”;
document.body.appendChild(heading);
const button = document.createElement(‘button’);
button.textContent = ‘Load Greeting’;
button.addEventListener(‘click’, () => {
import(‘./message.js’) // Dynamic import
.then(module => {
const greeting = module.greeting;
heading.textContent = greeting;
})
.catch(err => {
console.error(‘Error loading module:’, err);
});
});
document.body.appendChild(button);
“`
import('./message.js')
: This is a dynamic import. It returns a Promise that resolves with the module’s exports..then(module => ...)
: This code runs when the module is successfully loaded..catch(err => ...)
: This code handles any errors that occur during loading.
When you click the button, Webpack will load the message.js
module and its dependencies