Fontsource is designed to work with projects that bundle their CSS. You import their stylesheet and the bundler will place the fonts in your build directory and the CSS file will have the correct URL for the @font-face
src
.
Remix doesn’t bundle CSS and so while you can import their CSS file and add it to your links
, the URL to font will be incorrect. It is still possible to use Fontsource with Remix. We just need to create our own @font-face
declaration with the correct URL to the font (ideally, one that benefits from Remix’s asset fingerprinting). There’s a bit of manual set up, but once that’s done, you can serve the font on your site and benefit from updates for the font.
- Install your font:
npm install --save @fontsource/montserrat
- Create a directory for fonts in your the
app
directory so that you can fingerprint the font assets for long term caching. Run the following from your project root.mkdir app/fonts
- Link the
files
directory of the font to the yourapp/fonts
directory. Run the following from your project root.ln -s node_modules/@fontsource/montserrat/files app/fonts/montserrat
- In the layout that you need the font, import the font file you want. It’s a sym-link so autocomplete won’t work unfortunately.
import montserratVariableFontLatin from '~/fonts/montserrat/montserrat-latin-variable-wghtOnly-normal.woff2`;
- Define the
@font-face
using the font asset URL that we imported. We have to use a<style>
element to include this as we cannot set the URL as a custom property since they cannot be accessed in@font-face
declarations. Take a look at the corresponding CSS file in the@fontsource
Node module to know what to set here (especially for theunicode-range
andfont-weight
).const montserratFontFaceDeclaration = ` @font-face { font-family: 'Montserrat', sans-serif; font-style: normal; font-display: swap; font-weight: 100 900; src: url(${montserratVariableFontLatin}) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } `;
<head> <style dangerouslySetInnerHTML={{__html: montserratFontFaceDeclaration}} /> </head>
https://www.npmjs.com/package/@fontsource/montserrat