使用 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');
}
没有错误,否则只是编译...我已经读过(堆栈溢出/57590195 https://stackoverflow.com/questions/57590195/nextjs-self-hosted-fonts-loading)这表示我们应该使用静态路径,例如
@font-face {
font-family: 'font';
src: url('./static/fonts/Montserrat-Medium.woff2') format('woff2');
}
但该解决方案根本不起作用。它看起来几乎工作正常,因为错误(或引人注目的等待)停止了。
但如果你仔细观察,你的字体还没有加载。
然后我尝试了 fontfaceobserver,我很快就明白问题是一样的。因为你必须使用font-face
并且你不能将它与 NextJS 一起使用。
下载下一个字体后,我阅读了文档并查看了github 示例 https://github.com/rohanray/next-fonts-example.
这是我的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 https://github.com/bramstein/fontfaceobserver 456 KB
- ✗ https://github.com/rohanray/next-fonts https://github.com/rohanray/next-fonts1.89MB
- ? The
dangerouslySetInnerHTML
可以,但不是最好的
我猜的解决方案。 (我没试过)
- ✗ url('./static/fonts/font.woff2')
阅读更多 github 问题 https://github.com/zeit/next.js/issues/512
EDIT:
我尝试去适应什么杰斯珀我们 https://stackoverflow.com/users/2846463/jesper-we did https://stackoverflow.com/a/61913799/7942242.
我创造了/public/static/fonts/fonts.css
and /public/fonts/allMyfont.ttf
然后我导入 _var.scss 以将其与 sass 变量 @import "/public/static/fonts/fonts.css"; 一起使用import style.scss my var $font 并将“my/path/style.scss”导入到我的index.js(永远编译)
在我尝试了更接近的方法之后/public/static/fonts/fonts.css
与我的字体在同一文件夹中。然后在我的index.js 中。但那个人什么也没做。
这是实时代码代码沙盒 https://codesandbox.io/s/github/Florian-crg/byflo