Webpack:index.html 中的内联处理字体文件

Webpack: Inline processed font file in index.html

我正在使用 html-webpack-plugin,我想将我的散列字体文件插入到我的自定义 index.html 模板中。

index.html

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

然后我在输入文件 app.js 中导入字体 import "./fonts/inter.woff2"

我不知道如何获取已处理字体资源的引用。

据我所知,HTMLWebpackPlugin 有一个模板变量 htmlWebpackPlugin,其中包含 js 和 css 链接,它不会包含所有 webpack 资产。

我有一个替代方案,不是用js导入字体,而是导入一个有字体用法的css,这样,你可以配置webpack将css注入到html.

所以,它看起来像这样:

// index.js
import 'styles.css';


// styles.css
@font-face {
    font-family: Inter;
    src: url("./font.woff") format("woff2");
}

这个问题是我努力内联一些关键 CSS 的一部分,其中也包含我的 font-face

首先,follow thismini-css-extract-plugin根据词条提取CSS的指南。尽管我做的不同的一件事是我直接提供包含我的关键 CSS index.scss 的 SCSS 文件作为名为 critical:

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

然后在我的 index.html 中,我们将利用 webpack 的 compilationhtml-webpack-pluginhtmlWebpackPlugin 对象:

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

这就是你的内容 - 你的批评 index.scss 的内容内嵌在你的 index.html 中!