Skip to content
Fontsource Logo
Documentation

Webpack

Webpack can bundle Fontsource CSS and emit its referenced font files as versioned application assets. Webpack 5’s built-in Asset Modules replace the former file-loader setup.

1. Install the font and CSS loaders

npm install @fontsource-variable/open-sans
sh
npm install -D style-loader css-loader
sh

2. Configure Webpack

Add rules for CSS and font assets:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(woff2?|eot|ttf|otf)$/i,
        type: "asset/resource",
      },
    ],
  },
};
js

css-loader resolves the url() references in Fontsource CSS. style-loader adds the resulting stylesheet to the page. The asset rule emits the referenced font files without an additional loader.

3. Import and apply the font

// src/index.js
import "@fontsource-variable/open-sans/wght.css";
import "./styles.css";
js
/* src/styles.css */
body {
  font-family: "Open Sans Variable", sans-serif;
}
css

For production builds that extract CSS into separate files, use your existing CSS extraction plugin in place of style-loader. See Webpack’s Asset Modules guide and style-loader documentation for the underlying configuration.