Build pipeline

webpack-template

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.


What it is and what it solves

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.

Module graph and loader chains

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 · test loader chain — execution order output /\.s[ca]ss$/ import '@scss/styles.scss' sass-loader scss → css css-loader url() → modules MiniCssExtractPlugin.loader style-loader instead of it in dev app.[hash].css /\.m?js$/ excluding node_modules babel-loader presets: ['@babel/preset-env'] splitChunks: 'all' — shared code into its own chunk app.[hash].js 202.[hash].js /\.ts$/ · /\.jsx$/ no such files in the template babel-loader + preset-typescript / preset-react rules are here for later; nothing matches them today the same bundle png · svg · jpg · gif woff · woff2 · ttf · otf type: 'asset/resource' + use: ['file-loader'] — duplicated, see defects [hash][ext] plugins — they operate on the whole graph, not on a single file HtmlWebpackPlugin template templates/pages/ index.html → dist/index.html injects <script> and <link> itself for every emitted chunk + ~60 SEO / OG / CSP meta tags MiniCssExtractPlugin collects the css accumulated by its loader and writes it as a separate file instead of injecting into <head> name: filename('css') ESLintPlugin lints ./src in parallel with the build failOnError: isProd — in prod a lint error fails the build optimization.minimizer CssMinimizerPlugin — css TerserPlugin — js only when isProd: minimize: false in dev, the minimizer list is empty
The key difference from gulp: nothing here enumerates files. There is one entry point, 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.

How dev and prod differ

module.exports is an array of two configurations built from one shared object with Object.assign. The differences come down to five lines.

dev — npm run dev --config-name dev mode: 'development' devtool: 'eval' style-loader → <style> in <head> minimize: false filename: '[name].js' prod — npm run build --config-name prod mode: 'production' devtool: — MiniCssExtract → app.[hash].css CssMinimizer + Terser filename: '[name].[contenthash].js' plus devServer: https via mkcert, watchFiles, error overlay the same dist/ output.clean = true in both configurations
Both configurations reference the same object, 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.

Loaders and plugins

Everything declared in module.rules, plugins and optimization.

Rule / pluginWhat it doesTakesGives
sass-loaderCompiles SCSS with dart-sass, api: "modern", outputStyle: compressed.scss, .sassCSS text
css-loaderResolves @import and url(), turning them into module-graph dependenciesCSS texta JS module holding CSS
MiniCssExtractPlugin
.loader
Marks the CSS for extraction into its own file instead of script injection; replaced by style-loader in deva JS module holding CSSa contribution to app.[hash].css
style-loaderThe dev variant: inserts styles as a <style> tag at runtime, which gives hot replacement without a reloada JS module holding CSSinjection code in the bundle
babel-loaderTranspiles against the project's browserslist (> 0.25%, not dead); three preset sets for three extensions.js, .ts, .jsxES5-compatible JS
asset/resource
+ file-loader
Copies the binary file into the build and substitutes a URL for itimages, fontsa file in dist/ + URL
HtmlWebpackPluginTakes the template, wires up every emitted chunk itself, adds the meta-tag block and CSP, minifies in prodsrc/templates/pages/index.htmldist/index.html
MiniCssExtractPluginWrites the accumulated CSS as its own file with a content hashmodule graphdist/app.[hash].css
ESLintPluginLints ./src during the build; in prod failOnError stops it./src/**a report, or a halt
TerserPluginJS minification, only when isProdJS chunkscompressed chunks
CssMinimizerPluginCSS minification, only when isProdapp.[hash].csscompressed CSS
splitChunkschunks: 'all' — shared and vendor code goes into its own chunk, so it caches independently of the application codemodule graph202.[hash].js

Key excerpts

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.

Known defects

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.

Build output

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.

Open the built page

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.