Build pipeline
A starter on webpack 5: babel with three presets, SCSS through sass-loader and extracted
into its own file, ESLint inside the build, separate dev and prod configurations in one file, and a dev
server over https. Below: the module graph, the loader chains as they actually run, and exactly what
separates the two modes.
A build skeleton for projects that need modular JS, not just markup.
The starter solves the same problem as the gulp one — take the repetitive setup out of every new
project — by a different route. In gulp the pipeline is written as a sequence of file streams; in webpack
a single entry point drags in a dependency graph, and everything else is rules about what to do
with each kind of node in it. From that follows the one difference that matters in practice:
styles.scss ends up in the build not because someone named its path, but because
script.js has an import for it.
What is configured above the minimum: aliases (@scss, @img, @js)
instead of ../../ chains; splitChunks: 'all', which pulls dependencies into
their own chunk; content hashes in file names for caching; ESLint wired into the build and failing it on
an error in production; and a large block of SEO/Open Graph/Twitter meta that
HtmlWebpackPlugin injects into the markup.
Read straight off webpack.config.js. Loaders are shown in execution order;
the config lists them in reverse — the standard and most common source of confusion.
The diagram is wider than the screen — scroll it horizontally.
entry.app = ['@babel/polyfill', './assets/js/script.js'], and everything else gets into the
build through import. Order in a loader chain matters and is the reverse of the order
it is written in: the config says [MiniCssExtract.loader, css-loader, sass-loader], and it
runs bottom-up — sass first, and last the loader that decides where the result goes.
module.exports is an array of two configurations built from one shared object with
Object.assign. The differences come down to five lines.
vendorConfig, so they share one
output, one plugins array and one build directory with clean
turned on. As long as they are run one at a time (--config-name in the npm scripts) that
works; running webpack with no flag builds both in sequence into the same directory, and the
second wipes the first. On top of that, isDev is computed from
process.env.NODE_ENV once when the module loads, not from the mode field — so
the line mode: 'development' by itself does not switch the loader chain.
Everything declared in module.rules, plugins and optimization.
| Rule / plugin | What it does | Takes | Gives |
|---|---|---|---|
| sass-loader | Compiles SCSS with dart-sass, api: "modern", outputStyle: compressed | .scss, .sass | CSS text |
| css-loader | Resolves @import and url(), turning them into module-graph dependencies | CSS text | a JS module holding CSS |
| MiniCssExtractPlugin .loader | Marks the CSS for extraction into its own file instead of script injection; replaced by style-loader in dev | a JS module holding CSS | a contribution to app.[hash].css |
| style-loader | The dev variant: inserts styles as a <style> tag at runtime, which gives hot replacement without a reload | a JS module holding CSS | injection code in the bundle |
| babel-loader | Transpiles against the project's browserslist (> 0.25%, not dead); three preset sets for three extensions | .js, .ts, .jsx | ES5-compatible JS |
| asset/resource + file-loader | Copies the binary file into the build and substitutes a URL for it | images, fonts | a file in dist/ + URL |
| HtmlWebpackPlugin | Takes the template, wires up every emitted chunk itself, adds the meta-tag block and CSP, minifies in prod | src/templates/pages/index.html | dist/index.html |
| MiniCssExtractPlugin | Writes the accumulated CSS as its own file with a content hash | module graph | dist/app.[hash].css |
| ESLintPlugin | Lints ./src during the build; in prod failOnError stops it | ./src/** | a report, or a halt |
| TerserPlugin | JS minification, only when isProd | JS chunks | compressed chunks |
| CssMinimizerPlugin | CSS minification, only when isProd | app.[hash].css | compressed CSS |
| splitChunks | chunks: 'all' — shared and vendor code goes into its own chunk, so it caches independently of the application code | module graph | 202.[hash].js |
Four places that decide how the build behaves.
const isDev = process.env.NODE_ENV !== "production",
isProd = !isDev
const filename = ext => isDev ? `[name].${ext}` : `[name].[contenthash].${ext}`
The only mode switch in the whole file. The hash goes into the name in prod only: in dev
it would get in the way, producing a new file on every rebuild. The flip side is in the defects list —
isDev depends on an environment variable rather than on mode, so the mode is set
by the npm script through cross-env, and running webpack directly gives you
something other than what you expect.
{
test: /\.s[ca]ss$/,
use: [
isDev ? "style-loader" : MiniCssExtractPlugin.loader,
{ loader: "css-loader", options: { sourceMap: isDev } },
{ loader: "sass-loader", options: {
implementation: require.resolve("sass"),
api: "modern",
sassOptions: { outputStyle: "compressed" }
}}
]
}
The chain runs bottom-up. Swapping the top link is the only difference between the modes: in dev the styles live inside the bundle and are replaced on the fly, in prod they are extracted into a file the browser caches separately from the JS.
resolve: {
alias: {
"@": srcFolder,
'@img': path.join(srcFolder, 'assets/img'),
"@js": path.join(srcFolder, 'assets/js/'),
"@scss": path.join(srcFolder, 'assets/styles/')
},
extensions: ['.js', '.json', '.jsx', '.ts', '.tsx']
}
Aliases take ../../ out of the imports and make moving a file safe.
extensions lets you write import x from './modules/design' with no extension —
and it also explains why the rules cover .ts and .jsx: the starter assumes
TypeScript or React will be added to the project.
optimization: {
splitChunks: { chunks: 'all' },
minimize: isProd,
minimizer: isProd ? [ new CssMinimizerPlugin(), new TerserPlugin() ] : []
}
In the demo build this rule produces the second file, 202.[hash].js — that is
where @babel/polyfill from the entry point went. The point is caching: application code
changes often, dependencies rarely, and splitting them keeps the browser from re-downloading the second
along with the first.
An honest list. The first four are what had to be fixed: out of the box the build died before the config had even been read. The rest is still in the code.
require time
Cannot find module 'ajv/dist/compile/codegen'. The outdated
optimize-css-assets-webpack-plugin pulls ajv@6 into the root node_modules,
while ajv-keywords@5 (via schema-utils → mini-css-extract-plugin)
needs ajv@8. The plugin was replaced with css-minimizer-webpack-plugin, which was already
in the dependencies.fs.readFileSync for the dev-server certificate ran while the config was
being loaded, so a missing src/certs/webpack-2023+1.pem broke the production build
as well — and the repository holds only mkcert.exe, no .pem at all. Wrapped in
fs.existsSync with a fallback to http.HtmlWebpackPlugin had ./pages/index.html written into it,
while the only html file sits at src/templates/pages/index.html.assets/js/script.js alone, and no module imported
styles.scss. So sass-loader and MiniCssExtractPlugin were
configured but dead, and the page was built without a single style.
import '@scss/styles.scss' was added; that then surfaced @import "_fonts.scss"
and "_preloader.scss" against files with no underscore — fixed too.isDev is not tied to mode
The mode the loaders see comes from an environment variable; the configuration's
mode field has no effect on them. Running webpack --config-name dev without
NODE_ENV=development gives you webpack's dev mode but the prod loader chain. The only thing
holding this together is cross-env in the npm scripts.Object.assign({...}, vendorConfig) copies references, so dev and prod use
the same plugin instances, the same output and the same dist with
clean: true. Running both configurations in one pass means the second erases the first's
result.type: 'asset/resource' and file-loader at the same time
In webpack 5, asset/resource is the built-in replacement for
file-loader. Naming both in one rule is a conflict: the file gets processed twice. The
defect stays invisible in the demo build only because the single image (AuthCode.png) is
imported nowhere.CopyWebpackPlugin = import('copy-webpack-plugin') assigns a dynamic
import to a const, so the variable holds a promise; the block that uses it is commented
out, and as written the plugin would not work. devDependencies still carry
optimize-css-assets-webpack-plugin (the one that broke the build) and
eslint-loader, superseded by eslint-webpack-plugin.
@babel/polyfill has been deprecated since Babel 7.4 in favour of
core-js + regenerator-runtime.<title> is still Document. The CSP allows
'unsafe-inline' and 'unsafe-eval' in script-src, which throws
away most of the point of having a policy at all. git carries src/certs/mkcert.exe — a
4.7 MB Windows binary — and 57 MB of Yu Gothic fonts that cannot reach the build under any
circumstances, because fonts.scss is zero bytes.Preloader, Header,
Section 1, Article 1–3, Aside, Footer), and the
block SCSS partials are selectors with no properties. What is worth judging here is the configuration,
not the result.
After the fixes npm run build runs clean and produces index.html,
app.[hash].css, app.[hash].js and the vendor chunk 202.[hash].js.
The pipeline's output as it is: six placeholder blocks, styles linked as a separate content-hashed file, scripts split into two chunks, the whole meta-tag block injected by the plugin. The page is here as proof that the build works, not as a sample of markup.