TExcelTAD

Webpack Loaders & Plugins

Webpack's two extension points split the work cleanly:

  • A loader transforms one file into a JavaScript module as it's added to the graph: TypeScript to JS, Sass to CSS to JS, Markdown to an HTML string. Loaders are functions from source text to source text.
  • A plugin hooks into the whole compilation: it can add files, change chunks, define constants, or report on the build. Plugins are classes with an apply(compiler) method that taps into Webpack's hooks.

Loaders in a config

Rules match files by test (a regex on the path) and apply a list of loaders, run from last to first:

js
// typical frontend rules (these loaders come from npm)
module: {
  rules: [
    { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },          // or babel-loader / swc-loader / esbuild-loader
    { test: /\.css$/, use: ['style-loader', 'css-loader'] },                // css-loader runs first, then style-loader
    { test: /\.s[ac]ss$/, use: ['style-loader', 'css-loader', 'sass-loader'] },
    { test: /\.(png|svg|jpe?g)$/, type: 'asset' },                          // built in, no loader needed
  ],
}

Those third-party loaders aren't in this course's registry, but a loader is just a module exporting a function, so we can write our own and watch the mechanics for real.

Writing loaders

A loader receives the file's source as a string and returns JavaScript (or input for the next loader). this is the loader context: this.getOptions() reads options, this.resourcePath is the file.

bash · try it yourself
mkdir -p wp/src wp/loaders && cd wp
npm init -y > /dev/null && npm pkg set type=module
npm install -D webpack@5.112.2 webpack-cli@7.2.3 > /dev/null 2>&1
cat > loaders/md-loader.cjs <<'JS'
// Markdown (headings and paragraphs only) -> an ES module exporting HTML.
module.exports = function (source) {
  const html = source.trim().split(/\n\n+/).map((block) =>
    block.startsWith('# ') ? `<h1>${block.slice(2)}</h1>` : `<p>${block}</p>`).join('');
  return `export default ${JSON.stringify(html)};`;
};
JS
cat > loaders/shout-loader.cjs <<'JS'
// Runs BEFORE md-loader (loaders run right to left) and uppercases words listed in options.
module.exports = function (source) {
  const { words } = this.getOptions();
  return words.reduce((s, w) => s.replaceAll(w, w.toUpperCase()), source);
};
JS
printf '# Release notes\n\nThe new build is faster.\n\nIt is also smaller.\n' > src/notes.md
echo 'Licensed under MIT' > src/license.txt
cat > src/index.js <<'JS'
import notes from './notes.md';
import license from './license.txt';
console.log(notes);
console.log(license.trim());
JS
cat > webpack.config.js <<'JS'
import path from 'node:path';
export default {
  mode: 'production',
  entry: './src/index.js',
  output: { path: path.resolve('dist'), filename: 'main.js', clean: true },
  module: {
    rules: [
      { test: /\.md$/, use: ['./loaders/md-loader.cjs', { loader: './loaders/shout-loader.cjs', options: { words: ['faster', 'smaller'] } }] },
      { test: /\.txt$/, type: 'asset/source' },
    ],
  },
};
JS
npx webpack 2>&1 | grep -E 'asset main|\.md|\.txt|compiled'
node dist/main.js
asset main.js 161 bytes [emitted] [minimized] (name: main)
webpack 5.112.2 compiled successfully in 210 ms
<h1>Release notes</h1><p>The new build is FASTER.</p><p>It is also SMALLER.</p>
Licensed under MIT

shout-loader ran first (it's last in the use array), then md-loader turned the result into a module. The .txt file needed no loader at all: asset modules are built in since Webpack 5:

type Result
asset/source the file's text as a string
asset/resource the file is emitted to dist/; the import is its URL
asset/inline a data: URL
asset inline below 8 KB, otherwise a separate resource

Built-in plugins

Webpack ships a set of plugins as properties of the webpack package:

bash · try it yourself
mkdir -p wp/src && cd wp
npm init -y > /dev/null && npm pkg set type=module
npm install -D webpack@5.112.2 webpack-cli@7.2.3 > /dev/null 2>&1
cat > src/index.js <<'JS'
if (__DEBUG__) console.log('debug logging on');
console.log(`api: ${API_URL}`, '| version', PKG_VERSION);
JS
cat > webpack.config.js <<'JS'
import path from 'node:path';
import webpack from 'webpack';
export default {
  mode: 'production',
  entry: './src/index.js',
  output: { path: path.resolve('dist'), filename: 'main.js', clean: true },
  plugins: [
    new webpack.DefinePlugin({
      __DEBUG__: JSON.stringify(false),
      API_URL: JSON.stringify('https://api.example.com'),
      PKG_VERSION: JSON.stringify('3.1.0'),
    }),
    new webpack.BannerPlugin({ banner: 'acme-shop | (c) ACME | MIT', entryOnly: true }),
  ],
};
JS
npx webpack > /dev/null
cat dist/main.js; echo
cat dist/main.js.LICENSE.txt
node dist/main.js
/*! For license information please see main.js.LICENSE.txt */
(()=>{"use strict";console.log("api: https://api.example.com","| version","3.1.0")})();
/*! acme-shop | (c) ACME | MIT */
api: https://api.example.com | version 3.1.0

DefinePlugin replaces identifiers with code, hence JSON.stringify around strings. With __DEBUG__ known to be false, the whole if disappeared. BannerPlugin added the comment, and then Terser did something you might not expect: by default (extractComments) it moves licence-like comments out of the bundle into main.js.LICENSE.txt and leaves a one-line pointer behind. The minimizer here is minimizer-webpack-plugin (the package webpack 5.112 depends on; older Webpack 5 releases used terser-webpack-plugin, with the same option), running Terser; configure your own instance in optimization.minimizer with extractComments: false if you want banners to stay inline. Other useful built-ins: ProvidePlugin (auto-import a module where a free variable is used), IgnorePlugin, EnvironmentPlugin, ProgressPlugin.

Writing a plugin

A plugin taps hooks with a name. The most useful one for output is compilation.hooks.processAssets, where you can read and add files:

bash · try it yourself
mkdir -p wp/src && cd wp
npm init -y > /dev/null && npm pkg set type=module
npm install -D webpack@5.112.2 webpack-cli@7.2.3 > /dev/null 2>&1
echo 'console.log("shop");' > src/shop.js
echo 'console.log("admin"); console.log("more admin code");' > src/admin.js
cat > manifest-plugin.js <<'JS'
import webpack from 'webpack';
const { Compilation, sources } = webpack;

export class ManifestPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap('ManifestPlugin', (compilation) => {
      compilation.hooks.processAssets.tap(
        { name: 'ManifestPlugin', stage: Compilation.PROCESS_ASSETS_STAGE_REPORT },
        (assets) => {
          const manifest = {};
          for (const chunk of compilation.chunks) {
            for (const file of chunk.files) manifest[chunk.name] = { file, bytes: assets[file].size() };
          }
          compilation.emitAsset('manifest.json', new sources.RawSource(JSON.stringify(manifest, null, 2)));
        },
      );
    });
    compiler.hooks.done.tap('ManifestPlugin', (stats) => {
      console.log(`[manifest] ${Object.keys(stats.compilation.assets).length} assets written`);
    });
  }
}
JS
cat > webpack.config.js <<'JS'
import path from 'node:path';
import { ManifestPlugin } from './manifest-plugin.js';
export default {
  mode: 'production',
  entry: { shop: './src/shop.js', admin: './src/admin.js' },
  output: { path: path.resolve('dist'), filename: '[name].[contenthash:8].js', clean: true },
  plugins: [new ManifestPlugin()],
};
JS
npx webpack 2>&1 | grep -E 'manifest|compiled'
cat dist/manifest.json
[manifest] 3 assets written
asset manifest.json 134 bytes [emitted]
webpack 5.112.2 compiled successfully in 194 ms
{
  "shop": {
    "file": "shop.4c0f0cb6.js",
    "bytes": 43
  },
  "admin": {
    "file": "admin.336aefb0.js",
    "bytes": 75
  }
}

That's the pattern behind webpack-manifest-plugin and the HTML plugins: with hashed file names, the server or an index.html needs a map from "the shop entry" to "today's file name". The [contenthash:8] placeholder is the subject of the next lesson.

Test yourself

In use: ['style-loader', 'css-loader'], which loader runs first?

  1. style-loader
  2. css-loader
  3. Both in parallel
  4. Whichever is faster

Why do DefinePlugin values use JSON.stringify for strings?

  1. Webpack only accepts JSON
  2. Values are inserted as code, so a string must include its quotes
  3. To encrypt them
  4. To make them tree-shakeable

What is the difference between a loader and a plugin?

  1. Loaders are faster
  2. A loader transforms one module's source; a plugin hooks into the whole compilation
  3. Plugins only run in development
  4. There is none