How to load a font from node_modules with vite?

by darrion.kuhn , in category: Javascript , 2 months ago

How to load a font from node_modules with vite?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 2 months ago

@darrion.kuhn 

To load a font from the node_modules directory in Vite, you can use the @font-face CSS rule to define the font and then import it into your CSS using an import statement.


Here's an example of how you can load a font from the node_modules directory:

  1. First, install the font package using npm or yarn:
1
npm install font-package-name


  1. Next, create a CSS file (e.g., styles.css) in your project that will import the font:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@font-face {
  font-family: 'CustomFont';
  src: url('../node_modules/font-package-name/font-file.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: 'CustomFont', sans-serif;
}


In this example, replace CustomFont, font-package-name, and font-file.ttf with the appropriate values for your font.

  1. Import the CSS file into your entry JavaScript file (e.g., main.js):
1
import './styles.css';


  1. Make sure Vite is set up to handle CSS files by including the style plugin in your vite.config.js:
1
2
3
4
5
6
7
8
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    // Add the CSS plugin to handle CSS files
    style(),
  ],
});


After following these steps, your font should be loaded from the node_modules directory and applied to your website's content.