Reputation: 371
I'm attempting to use a @font-face declaration in my scss file.
The correct CSS rule is getting applied so the font-face declaration seems fine. The path is getting resolved as well so that's no issue. And, webpack throws no errors so it doesn't appear to be any kind of a loader issue. But in the end, the font is still not being rendered by the browser. (see image)
As of Webpack 5, the documentation states that you can declare in the rules "type: 'asset/resource'" to correctly load an asset such as a font or an image. It's working for the image I loaded, but not for the font.
CSS:
@font-face {
font-family: 'Yusei Magic', sans-serif;
font-style: normal;
font-weight: 400;
src: url('./assets/fonts/yusei-magic/YuseiMagic-Regular.ttf')
format('truetype');
}
Webpack config:
module: {
...
rules: [
...
{
test: /\.ttf$/,
type: 'asset/resource',
},
],
},
Upvotes: 13
Views: 15878
Reputation: 179
As you use url('./assets/fonts/yusei-magic/YuseiMagic-Regular.ttf')
in your css which is a relative path, in order to webpack can resolve these kind of relative paths in your CSS files you should use resolve-url-loader
as the following configuration in rules array in your webpack.config.js
file:
other loaders ...
{
test: /\.(sa|sc|c)ss$/, // styles files
use: ["style-loader",'css-loader' ,'resolve-url-loader', {
loader: 'sass-loader',
options: {
sourceMap: true,
}
}],
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/, // to import images and fonts
loader: "file-loader",
},
the first one for loading css/scss files with resolved URLs and the second one for loading fonts (and of course this pattern also load images too :)).
Upvotes: 3
Reputation: 371
When you're defining a @font-face
declaration, on the font-family
property, you must only write a string indicating how you will reference the font in your later styles.
In other words, I erroneously included "sans-serif" after "Yusei Magic" on the font-family
property. This didn't throw an error, but it's incorrect CSS and thus was the source of my error. Thanks for anyone who chimed in!
Upvotes: 7
Reputation: 10529
Since the font is referenced by the css function url()
, the responsible Webpack loaders needs to be added too.
If not installed:
npm install --save-dev style-loader css-loader
The rules stack should look like this:
rules: [
...
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
...
]
Details can be found here (loading-css) and here (loading-fonts).
css-loader
interprets @import
and url()
like import/require()
and will resolve them.
Upvotes: 2