NextJS 导出 - 如何正确包含字体

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

我在 NodeJs 不可用的服务器上托管一个网站。我正在使用

npm run export
并在服务器上部署
out
文件夹的内容。

我设法解决了提供 CSS、JS 和图像的问题,但我不知道如何提供字体。

我在

globals.css
中导入字体,它在本地工作:

@font-face {
  font-family: "Roboto Light";
  src: url('../public/fonts/Roboto-Light.ttf');
}

@font-face {
  font-family: "Roboto Black";
  src: url('../public/fonts/Roboto-Black.ttf');
}

@font-face {
  font-family: "Due Credit Regular";
  src: url('../public/fonts/Due-Credit-Regular.otf');
}

@font-face {
  font-family: "Otamendi";
  src: url('../public/fonts/Otamendi.ttf');
}

@font-face {
  font-family: "Compacta Regular";
  src: url('../public/fonts/Compacta-Regular.ttf');
}

我尝试了这个解决方案,但它不起作用。

deployment fonts next.js
4个回答
1
投票

我将介绍我的解决方案。

首先,您需要将字体文件(*.ttf、*.woff)放置在公共目录中。假设您的字体文件位于 /public/fonts 中。

/public
  /fonts
   Roboto-Bold.ttf
   Roboto-Bold.woff
   Roboto-Bold.woff2
   Roboto-Italic.ttf
   Roboto-Italic.woff
   Roboto-Italic.woff2
   Roboto-Regular.ttf
   Roboto-Regular.woff
   Roboto-Regular.woff2

其次,在 /public/fonts 中创建 fontstyle.css 并编写如下内容。

@font-face {
    font-family: 'Roboto';
    src: url('./Roboto-Italic.woff2') format('woff2'),
        url('./Roboto-Italic.woff') format('woff'),
        url('./Roboto-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
    font-display: swap;
}

@font-face {
    font-family: 'Roboto';
    src: url('./Roboto-Bold.woff2') format('woff2'),
        url('./Roboto-Bold.woff') format('woff'),
        url('./Roboto-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
    font-display: swap;
}

@font-face {
    font-family: 'Roboto';
    src: url('./Roboto-Regular.woff2') format('woff2'),
        url('./Roboto-Regular.woff') format('woff'),
        url('./Roboto-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
    font-display: swap;
}

第三,在根组件或应用程序组件中导入 fontstyle.css。

index.js

import 'public/fonts/fontstyle.css';
...

或者,如果您已经在项目根目录中配置了 jsconfig.json,则声明 public 目录并使用它。

jsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            ...
            "@public/*": [
                "public/*"
            ],
        }
    }
}

index.js

import '@public/fonts/fontstyle.css';
...

然后您可以在组件中使用 Roboto 字体系列。 全局.css

.myoddbtn{
   font-family: Roboto;
   font-size: 14px;
   font-weight:400;
}

测试按钮.jsx

export default function TestButton(){
   return (
     <button className="myoddbtn">
        Font-family:Roboto
     </button>

   )
}

0
投票

尝试删除链接中的“../public”部分:您的 js 包将位于生产中的不同文件夹中。


0
投票

在这里尝试了其他答案但没有成功。最终对我来说问题是“下次导出”期间的路径在除了 css 文件之外的所有地方都被重写。不幸的是,所提出的解决方案并没有解决这个问题。

但是我最终使用了另一个类似的解决方案在此处找到的另一个堆栈溢出问题此解决方案也使用replace-in-file来重写css中的路径。

只是想在这里为像我一样首先发现这个问题的人留下答案。


0
投票

我也有同样的问题。我的解决方案与其他路径黑客类似。 在out/_next_static/css/中。我用“../../../_next/”替换了所有“/_next”路径。 - 现在它找到了 woff 文件。

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