I have a webpack4+babel bundler setup for a react web app. In a LESS file, I reference a local font. This font gets copied over to the dist
folder on build and its filename is hashed. I want to be able to preload this font.
Here is my LESS file:
@font-face {
font-family: 'Test';
src: url('../fonts/test.ttf') format('truetype');
font-weight: 400;
}
I have tried the following approaches but so far with no success:
- Add custom import to my app's main JS file.
import(/* webpackPreload: true */ "../fonts/test.ttf");
Here is my .babelrc
file:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-syntax-dynamic-import"
]
}
Running webpack
does not produce preload directions anywhere as far as I can see in the outputted html - I have searched through the dist
folder contents and found nothing.
- preload-webpack-plugin
I add this to my webpack.config.js
file:
plugins: [
new HtmlWebpackPlugin(),
new PreloadWebpackPlugin({
rel: 'preload',
as(entry) {
if (/\.css$/.test(entry)) return 'style';
if (/\.woff$/.test(entry)) return 'font';
if (/\.png$/.test(entry)) return 'image';
return 'script';
}
})
]
This creates preloads for the JS script file bundles but not for the CSS and fonts.
Any ideas on how to get this to work?