在Vue3/Vite/Rollup中预加载导入的字体

问题描述 投票:0回答:1

如何在 Vue3(vite/rollup)应用程序中预加载从 npm 包导入的字体?

eg:我引用了材质字体库:

npm install --save material-symbols

并将其导入到main.js中:

import 'material-symbols';

除了页面加载时 FOUT 闪烁之外,字体工作正常,因此我想预加载它,但如何获取资源的 URL 并将其放入文档头?

我发现的东西:

  • Vite 文档提到了如何获取导入资产的 URL,但这仅适用于 js。如何将 URL 放入文档头?

  • 本页讨论使用

    @/
    语法引用静态资源,但这只适用于 vue 模板 - 同样,不适用于文档头

  • 我不能只是猜测最终的资产名称,因为打包后它最终会变成类似“/assets/material-symbols-outlined.a9af8db1.woff2”的东西


跟进:我最终没有找到一个好的解决方案,但最终做了以下事情:

  1. 切换到较小版本的材料符号字体,只有一个粗细。 (2Mb 降至 200K)。

  2. 编写了一个小的后处理bash脚本(见下文)来计算出目标文件名,并使用sed将预加载链接修补到打包的index.html正文头中。

此外,我正在考虑将每个符号的使用连字切换为 unicode html 实体。在字体加载之前连字很长,导致布局在字体加载之前出现严重错误。例如:在加载连字文本之前,类似于“设置”,然后将其简化为单个符号字符。

#!/bin/bash

# Find name of the asset file
newfile=$(basename `ls dist/assets/material-symbols-outlined*`)

# Insert into head
mv dist/index.html dist/index.orig.html
expr='s/(<title>)/<link rel="preload" crossorigin href="\/assets\/'$newfile'" as="font">\n    \1/'
sed -r "$expr" dist/index.orig.html > dist/index.html
javascript vuejs3 webfonts rollupjs preload
1个回答
0
投票

对于带有 Vite 插件Laravel,您可以通过在刀片模板中使用

Vite::asset()
helper 来实现上述目的。例如:

<link rel="preload" href="{{ Vite::asset('resources/fonts/icofont.woff2') }}" as="font" />

这将在

npm run dev
中使用正确的临时 URL,并将被正确的资产路径替换,包括
npm run build
上的版本后缀哈希。

© www.soinside.com 2019 - 2024. All rights reserved.