PostCSS plugin that transforms @fontsource src CSS properties values to
point URLs to your own custom directory.
Installation
npm add --save-dev postcss-fontsource-url
Usage
Move the @fontsource fonts to your public directory:
📁 dist
└── 📁 assets
└── 📁 fonts
├── roboto-mono-latin-400-normal.woff
└── roboto-mono-latin-400-normal.woff2/* stylesheet.css */ @import '@fontsource/roboto-mono/400.css';
// postcss.config.mjs import postcssImport from 'postcss-import'; import postcssFontsourceUrl from 'postcss-fontsource-url'; export default { plugins: [ postcssImport, postcssFontsourceUrl({directory: '/assets/fonts'}), ], };
The imported CSS will be transformed to something like this:
@font-face { font-family: 'Roboto Mono'; font-style: normal; font-weight: 400; src: url('/assets/fonts/roboto-mono-latin-400-normal.woff2') format('woff2'), url('/assets/fonts/roboto-mono-latin-400-normal.woff') format('woff'); }
From the original CSS:
@font-face { font-family: 'Roboto Mono'; font-style: normal; font-weight: 400; src: url('./files/roboto-mono-latin-400-normal.woff2') format('woff2'), url('./files/roboto-mono-latin-400-normal.woff') format('woff'); }
Alternative
If you need a more specific solution for the problem, use postcss-url
directly:
// postcss.config.mjs import postcssUrl from 'postcss-url'; export default { plugins: { postcssUrl({ url(asset) { // Rewrite @fontsource fonts URLs to use the `/assets/fonts` folder // instead of the default `./files/` path. if (asset.url.startsWith('./files/')) { return `/assets/fonts/${asset.url.slice('./files/'.length)}`; } return asset.url; }, }), }, };