【发布时间】:2020-09-06 14:17:08
【问题描述】:
使用 NextJS 的字体
我已经阅读了有关如何在 NextJS 中使用自托管字体的不同主题。
我在[ wait ] compiling ... 做的时候得到了什么:
@font-face {
font-family: 'montserrat';
src: url('./mypath/Montserrat-Medium.woff2') format('woff2'),
url('./mypath/Montserrat-Medium.woff') format('woff'),
url('./mypath/Montserrat-Medium.ttf') format('truetype'),
url('./mypath/Montserrat-Medium.svg#Montserrat-Medium') format('svg');
}
没有错误,或者只是编译...我读过 (stackoverflow/57590195) 说我们应该使用像
这样的静态路径@font-face {
font-family: 'font';
src: url('./static/fonts/Montserrat-Medium.woff2') format('woff2');
}
但该解决方案根本不起作用。它似乎工作正常,因为错误(或令人信服的等待)停止了。 但是,如果您仔细观察,您的字体并未加载。
然后我尝试了fontfaceobserver,我很快就明白问题会是一样的。因为你必须使用font-face,而不能与NextJS一起使用。
下载下一个字体后,我阅读了文档并查看了the github exemples。
这是我的 next.config.js 灵感来自他们的。
const withSass = require('@zeit/next-sass');
const withCSS = require("@zeit/next-css");
const withFonts = require('next-fonts');
module.exports = withFonts(
withCSS(
withSass({
enableSvg: true,
webpack(config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
});
return config;
}
})
)
);
我的字体路径public/static/fonts。
这就是我尝试使用它的方式。
...
function MainIndex() {
...
return (
<>
...
<style jsx>{`
@font-face {
font-family: 'Montserrat';
src: url('./static/fonts/Montserrat-Medium.ttf');
}
h1 {
font-family: 'Montserrat';
}
`}</style>
</>
)
}
...
我找到的解决方案
- ✗https://github.com/bramstein/fontfaceobserver 456 KB
- ✗https://github.com/rohanray/next-fonts 1.89 MB
- ?
dangerouslySetInnerHTML可以工作,但不是最好的 我猜的解决方案。 (我没试过) - ✗ url('./static/fonts/font.woff2')
Read more one the github issue
编辑:
我创建了/public/static/fonts/fonts.css 和/public/fonts/allMyfont.ttf 然后我导入了_var.scss 以将它与sass 变量@import "/public/static/fonts/fonts.css" 一起使用;导入 style.scss my var $font 并将“my/path/style.scss”导入到我的 index.js(永远编译)
在我尝试了一种更接近的方法之后,仍然/public/static/fonts/fonts.css 将我的字体放在同一个文件夹中。然后在我的 index.js 中。但是那个什么都不做。
这里是实时代码CodeSandBox
【问题讨论】:
-
这里只是一个简短的说明,您不应该在 Web 上使用 TTF,因为它们是未优化的文件。如果您有 TTF,则可以使用 Google 的
woff2cli 工具(与名为woff2_compress的工具捆绑)将 TTF 文件转换为 WOFF2 压缩文件,以便在您的网站上使用。 -
我在搜索这个主题时犯了一个愚蠢的错误:我字体的文件扩展名是大写的(.TTF 不是 .ttf)????♂️
标签: javascript reactjs fonts next.js