# Webpack [#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 [#1-install-the-font-and-css-loaders]

```sh
npm install @fontsource-variable/open-sans
yarn add @fontsource-variable/open-sans
pnpm add @fontsource-variable/open-sans
bun add @fontsource-variable/open-sans
```

```sh
npm install -D style-loader css-loader
yarn add -D style-loader css-loader
pnpm add -D style-loader css-loader
bun add -D style-loader css-loader
```

## 2. Configure Webpack [#2-configure-webpack]

Add rules for CSS and font assets:

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

`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 [#3-import-and-apply-the-font]

```js
// src/index.js
import "@fontsource-variable/open-sans/wght.css";
import "./styles.css";
```

```css
/* src/styles.css */
body {
  font-family: "Open Sans Variable", sans-serif;
}
```

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](https://webpack.js.org/guides/asset-modules/) and
[`style-loader` documentation](https://webpack.js.org/loaders/style-loader/)
for the underlying configuration.
