Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
A from-scratch walk through a frontend build: webpack 5 builds the dependency graph, babel-loader hands JavaScript to Babel, HtmlWebpackPlugin writes the page, the dev server reloads it, and loaders handle CSS and images. The complete config was built and run in the dev server with webpack 5.112 and Babel 8; the native HTML variant that is replacing the plugin was built separately.

Vite and Next.js hide the build step, which is great until it breaks. Then you need to know what a bundler and a transpiler actually do. This guide is for frontend developers who have only used ready-made setups. You will build a small webpack and Babel pipeline from an empty folder, one step at a time. By the end you can read any webpack.config.js and tell what each line does.
This is part 26 of the Frontend & JavaScript Fundamentals series. The previous part, automating code quality with ESLint, Prettier and Husky, checks your code before it lands. This part turns that code into files a browser can load.
Key takeaways
- webpack starts at an entry file, follows every import, and writes bundles. Loaders teach it new file types; plugins do everything else.
- Babel rewrites modern JavaScript for older browsers. In Babel 8, no
targetssetting means the browserslistdefaultsquery. - Put
[contenthash]in file names so browsers can cache them, and let a plugin or webpack itself write the HTML that points to them.
How a bundler works
webpack is a static module bundler: it builds a dependency graph from one or more entry points and combines the modules into bundles, as the webpack concepts page puts it. In practice it does four things:
- Start at an entry file, such as
src/index.js. - Follow every
importto build the graph of files. - Transform files that aren't plain JavaScript, using loaders.
- Write the result to an output folder as static files.
Two words come up all the time. A loader turns a file type into a module webpack can use, such as Babel for JavaScript or css-loader for CSS. A plugin handles wider jobs, such as writing an HTML page or tuning the bundle. Out of the box, webpack reads JavaScript and JSON. The docs now also describe newer built-in CSS and HTML handling, and the native HTML guide still marks that part experimental.
Step 1: Start from an empty folder
mkdir build-pipeline
cd build-pipeline
npm init -y
npm install --save-dev webpack webpack-cli
Open the new package.json. In the test for this post, npm 11 added a "type": "commonjs" line and npm 10 did not. Delete that line if you see it. With it, webpack treats your .js files as CommonJS, and the build fails on the first import with "'import' and 'export' may appear only with 'sourceType: module'".
Create this layout:
build-pipeline/
├── src/
│ ├── assets/logo.svg
│ ├── styles/main.css
│ ├── index.js
│ ├── template.html
│ └── utils.js
├── babel.config.json
├── package.json
└── webpack.config.js
Put any small SVG in logo.svg and one CSS rule in main.css. Then add a little modern JavaScript, so there is something for Babel to work on:
// src/utils.js
export const logMessage = (message) => {
console.log(`[app] ${message}`);
};
export const wait = (ms) =>
new Promise((resolve) => setTimeout(() => resolve('Done'), ms));
// src/index.js
import './styles/main.css';
import logo from './assets/logo.svg';
import { logMessage, wait } from './utils.js';
document.getElementById('logo-img').src = logo;
logMessage('Starting...');
wait(1000).then((result) => logMessage(result));
Step 2: Write the webpack config
webpack has not needed a config file since version 4, the concepts page notes. You want one anyway, so every choice is written down. The file is a Node.js module. Export a function instead of an object, and webpack passes it the mode you chose on the command line:
// webpack.config.js (first version)
const path = require('path');
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production';
return {
mode: isProduction ? 'production' : 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
clean: true,
},
devtool: isProduction ? 'source-map' : 'eval-source-map',
};
};
What each key does:
modeturns on the built-in defaults for development or production. webpack's own default isproduction, but in this config, leaving out--modegives development, becauseargv.modeis then undefined.entryis the root of the dependency graph.outputsays where bundles go.clean: trueemptiesdistbefore each build.devtoolpicks the kind of source map, so the browser's debugger shows your source code, not the bundle.
The [contenthash] part is about caching. The webpack caching guide explains that the hash changes only when the file's content changes. So a browser can keep a file for a long time, and a new release gets a new URL.
Step 3: Add Babel
Babel turns modern syntax into code older browsers can run. @babel/preset-env is the preset that picks the transforms for you, based on the browsers you target. You need three packages:
npm install --save-dev babel-loader @babel/core @babel/preset-env
Keep the Babel settings in their own file. The babel-loader README notes that loader options are merged with Babel config files such as babel.config.json.
{
"presets": [["@babel/preset-env", { "targets": "defaults" }]]
}
"defaults" is a browserslist query that covers most modern browsers. Babel 8 uses it anyway when you set no targets, according to the Babel options page. Writing it down makes the choice visible. Change it if you must support older browsers.
Then tell webpack to send JavaScript through Babel:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
The exclude line matters. The babel-loader README advises you to transform as few files as possible, and packages in node_modules are usually already compiled.
Step 4: Generate the HTML page
Each build writes a new hashed file name, so you can't hand-write the <script> tag. html-webpack-plugin writes the page for you and adds the tags.
npm install --save-dev html-webpack-plugin
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<img id="logo-img" alt="Logo" width="64" height="64" />
</body>
</html>
Save that as src/template.html, then add the plugin to the config:
const HtmlWebpackPlugin = require('html-webpack-plugin');
// inside the returned config object
plugins: [
new HtmlWebpackPlugin({
title: 'Build pipeline demo',
template: './src/template.html',
}),
],
The plugin is now deprecated
The html-webpack-plugin README now marks the plugin as deprecated, because webpack can write the HTML itself. Existing setups keep working. The replacement, experiments.html, is still experimental: the webpack native HTML guide expects it to become the default in webpack 6.
The native version makes the HTML file the entry. The page loads its own script, and webpack rewrites the URLs to the hashed names:
// native HTML instead of the plugin (experimental)
entry: { index: './src/index.html' },
experiments: { html: true },
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
htmlFilename: '[name].html',
clean: true,
},
Here src/index.html is the template above with a fixed <title> and a <script type="module" src="./index.js"></script> line before </body>. In a test build, leaving out htmlFilename gave the page a hashed name too, such as index.7a4b9cdf695624ac53e8.html.
| Option | What it does | Trade-off | When to use |
|---|---|---|---|
html-webpack-plugin |
Fills a template and injects script tags | Deprecated, but stable and widely documented | Existing projects, and new ones until native HTML is stable |
experiments.html |
Treats an HTML file as the entry | Experimental; behaviour can still change | Trying the webpack 6 direction on a side project |
Step 5: Run a dev server
Building after every change is slow. webpack-dev-server rebuilds when you save and updates the page.
npm install --save-dev webpack-dev-server
devServer: {
port: 8080,
open: true,
hot: true,
historyApiFallback: true,
},
hot turns on Hot Module Replacement, which swaps changed modules without a full reload. historyApiFallback serves index.html in place of 404 responses, which single-page app routes need. Both are described on the webpack DevServer page. You don't need a static setting for dist: in a test run, the dev server served the built page without one.
Add two scripts to package.json:
"scripts": {
"dev": "webpack serve --mode development",
"build": "webpack --mode production"
}
Step 6: Import CSS and images
With loaders, a CSS file or an image is just another import.
npm install --save-dev style-loader css-loader
// add to module.rules, after the Babel rule
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
Loaders in a chain run from right to left, the webpack loaders page explains. So css-loader reads the CSS and resolves its imports first, then style-loader puts it on the page. Swap them and the build breaks.
// Wrong: style-loader would receive raw CSS it can't handle
use: ['css-loader', 'style-loader'],
// Right: css-loader runs first, style-loader last
use: ['style-loader', 'css-loader'],
asset/resource is built into webpack 5, so images need no extra loader. The asset management guide shows that the import gives you the final URL, and the file is copied to dist with a hashed name.
Step 7: Build for production
Production mode turns on most optimizations by itself. The webpack mode page lists, among others:
- Minification:
optimization.minimizeis on. - Tree shaking:
usedExportsmarks exports nobody imports, so the minifier can drop them. - Module concatenation: several modules are joined into one scope.
To move library code into its own file, add splitChunks:
optimization: {
splitChunks: {
chunks: 'all',
},
},
Your code then changes often, and the library file keeps its hash and its cache. Splitting has conditions, though. The SplitChunksPlugin page says a new chunk is created only if it would be bigger than 20 KB in production. In a test build whose only library code was the small CSS runtime, webpack wrote one bundle. With React added, the production build wrote a second file with a numeric name, 607.7d92455856cc7213e3bf.js, holding the library code.
The complete config
Here is every step in one file. This exact file, with the files above, built without errors and ran in the dev server.
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production';
return {
mode: isProduction ? 'production' : 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
clean: true,
},
devtool: isProduction ? 'source-map' : 'eval-source-map',
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Build pipeline demo',
template: './src/template.html',
}),
],
devServer: {
port: 8080,
open: true,
hot: true,
historyApiFallback: true,
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
};
};
Checked against webpack@5.112.2, webpack-cli@7.2.3, webpack-dev-server@6.1.0, html-webpack-plugin@5.6.8, babel-loader@10.1.1, @babel/core@8.0.9, @babel/preset-env@8.0.7, css-loader@7.1.5 and style-loader@4.0.0 on Node.js 22.23.2, 2026-10-29. The Babel 8 migration guide says all Babel 8 packages require Node.js ^22.18.0 || >=24.11.0.
Fixed in this version
The earlier version installed a type-loader package that doesn't exist, pointed at a template file it never created, and used port 3000 with a static folder the dev server doesn't need. Those are gone, and the native HTML option is new.
Why this is worth knowing
Next.js and Vite run steps like these for you. Knowing the steps helps in three places:
- "Module not found" errors: you know webpack follows imports from the entry and which rule should match each file.
- Bundle size: you know where tree shaking and chunk splitting happen, and why a 15 KB library doesn't get its own file.
- Bigger setups: micro frontends with Module Federation are built on this same config.
Next in the series, server-side rendering looks at what happens when the server, not the browser, builds the first HTML.
Frequently asked questions
Do I still need webpack if I use Vite or Next.js?
Not directly. Those tools run their own build steps, so you rarely touch webpack yourself. The ideas still carry over: entry, loaders or plugins, hashed output and chunk splitting appear in every bundler.
What is the difference between a loader and a plugin?
A loader works on one file at a time and turns it into a module, such as CSS into JavaScript. A plugin hooks into the whole build, for example to write an HTML page or split chunks. The webpack concepts page uses the same split.
Why does my build fail on import with "sourceType: module"?
Your package.json probably has "type": "commonjs", which some npm versions add on npm init -y. webpack then parses your .js files as CommonJS. Delete the line and build again.
Do I need Babel at all in 2026?
It depends on your targets. If every browser you support runs modern syntax, Babel has little left to do. It still matters for older browsers and for syntax such as JSX, which browsers can't read.
Should I switch from html-webpack-plugin to native HTML now?
Not for production yet, as a rule of thumb. The plugin is deprecated but works, and the webpack guide still calls native HTML experimental. Try it on a side project, and plan the move for webpack 6.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- webpack: Concepts
- webpack: Loaders
- webpack: Mode
- webpack: Caching guide
- webpack: Asset management guide
- webpack: DevServer configuration
- webpack: SplitChunksPlugin
- webpack: Native HTML guide
- html-webpack-plugin README
- babel-loader README
- Babel: @babel/preset-env
- Babel: Upgrade to Babel 8
- Babel: Options (targets)
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead



Comments
Loading comments...