Search code examples
reactjswebpackhtml-webpack-plugin

Webpack: Inline processed font file in index.html


I'm using html-webpack-plugin and I would like to insert my hashed font file to my custom index.html template.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
     <style>
        @font-face {
          font-family: Inter;
          src: url("<%= ?????? %>") format("woff2");
        }
     </style>

And I import the font in my entry file app.js like import "./fonts/inter.woff2"

I can't figure out how to get the reference of the processed font asset.


Solution

  • This question was part of my effort to inline some critical CSS which contains my font-face too.

    First, follow this mini-css-extract-plugin guide to extract CSS based on entry. Though one thing I did differently was I directly provide the SCSS file that contains my critical CSS index.scss as a separate entry chunk named critical:

    // webpack.config.js
    module.exports = {
      entry: {
        app: 'index.js',
        critical: path.resolve(__dirname, "../src/index.scss")
      },
    

    Then in my index.html we will utilize the webpack's compilation and html-webpack-plugin's htmlWebpackPlugin object:

    // index.html
    <style>
       <%= compilation.assets[htmlWebpackPlugin.files.chunks.critical.css[0]].source() %>
    </style>
    

    And there you have it- The content of your critical index.scss being inlined in your index.html!