Currently I have 3 fonts that I want to add to my React project:a, a light, a bold.
My file structure:
/src
├── /fonts/
│ ├── /A.ttf
│ ├── /A-
As of webpack 5 you can use built-in asset modules instead. From the guide here, add this to module.rules
to load .ttf files:
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
Webpack requires a font loader to load font files present in your project. you are using a file loader to load fonts. Change
{
test: /\.(ttf|eot|woff|woff2)$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]'
}
to
{
test: /\.ttf$/,
use: [
{
loader: 'ttf-loader',
options: {
name: './font/[hash].[ext]',
},
},
]
}
by installing a font loader in your project like TTF Loader from NPM.
Using 'ttf-loader' from npm worked perfectly for me.
https://www.npmjs.com/package/ttf-loader
module: {
rules: [
{
test: /\.ttf$/,
use: [
{
loader: 'ttf-loader',
options: {
name: './font/[hash].[ext]',
},
},
]
}
]
}
Prefix the font path with ~
, to tell Webpack that this is not a relative import
https://github.com/webpack-contrib/sass-loader#imports