I use Vite with React + SCSS.
And I have fonts.scss where I use all my fonts for project:
@font-face {
font-family: "JosefinSans";
src: url("./JosefinSans-Regular.ttf") format("truetype");
font-weight: 400;
}
@font-face {
font-family: "JosefinSans";
src: url("./JosefinSans-Bold.ttf") format("truetype");
font-weight: 700;
}
But when I try to import my fonts on different path of my project like this:
@import "./assets/fonts/fonts.scss";
@import "./assets/colors/colors.scss";
body {
margin: 0;
font-family: "JosefinSans";
background-color: $border-light;
}
My fonts are not working. They only work when I compile to .css and use import with a .css file.
I tried checking if it works with .css files, and it does. However, I only want to use .scss in my project.
In the package.json file, I have sass, and I checked if any other .scss code like variables works. Everything works, but the fonts don’t work.
3
Answers
There seems to be an issue with how the path is resolved when importing fonts from a SCSS file. Make sure routes are configured correctly.
Check Vite’s configuration for SCSS:
Check if the font files are copied to the output directory:
vite.config.js:
Please check my solution and leave me feedback if it’s not working so that I can fix it.
I will offer another solutions.
In Sass, there are two types of @import statements: @import and @import url(). Both are used for importing stylesheets, but they have subtle differences:
@import:
The @import rule is a Sass-specific feature and does not require the url() syntax.
It is used to import Sass or CSS files into your Sass stylesheet.
When using @import, Sass will compile the imported stylesheet directly into the current stylesheet, combining all styles into a single file.
The file path specified in @import is resolved relative to the current Sass file’s location.
@import 'path/to/your/file';
@import url():
The @import url() syntax is a standard CSS function used to import external resources, such as fonts or stylesheets, and is often used to import external resources from the web, such as fonts hosted on a CDN.
Using @import url() causes the specified resources (e.g. font files) to be dynamically loaded by the browser when the stylesheet is parsed.
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
You can try using using ~ before the path so vite will resolve the path correctly relative to your project root also make sure that you have the right path so your code would be like this