How to preload a CSS @font-face font that is bundled by webpack4+babel?

Frank picture Frank · Mar 28, 2019 · Viewed 14.7k times · Source

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:

  1. 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.

  1. 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?

Answer

Pavel picture Pavel · Aug 29, 2020

was able to make it work on webpack4 by installing version 3beta and using while list option:

yarn add -D [email protected]

new PreloadWebpackPlugin({
        rel: 'preload',
        as: 'font',
        include: 'allAssets',
        fileWhitelist: [/\.(woff2?|eot|ttf|otf)(\?.*)?$/i],

    }),