使用NextJS加载字体
我阅读了关于如何在NextJS中使用自托管字体的不同话题。
当我执行以下操作时:
我得到了[等待]编译...
@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中使用它。
在我下载了next-font之后,我阅读了文档并查看了GitHub示例。
这里是我的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')
编辑:
我创建了/public/static/fonts/fonts.css
和/public/fonts/allMyfont.ttf
,然后我在_var.scss中导入以使用sass变量@import "/public/static/fonts/fonts.css";导入style.scss我的var $font和import "my/path/style.scss"到我的index.js(编译永远失败)
之后,我尝试了一个更接近的方式,仍然是/public/static/fonts/fonts.css
,并将我的字体放在同一个文件夹中。然后在我的index.js中,但那个什么也没做。
这里是在线代码CodeSandBox
woff2
命令行工具(其中包含一个名为woff2_compress
的工具)将TTF文件转换为WOFF2压缩文件,以便在你的网站上使用。 - vhs