首页 > 解决方案 > 如何在域的子路径下的 Next.js 应用程序上使用自定义字体?

问题描述

我有一个 Next.js 应用程序部署在域的子路径下(例如example.com/my-next-js-app)。对于捆绑脚本和样式,我可以使用 Next.js 配置解决它们:

const isProd = process.env.NODE_ENV === 'production';
module.exports = {
  basePath: isProd ? '/my-next-js-app' : '',
};

对于图像,我可以创建一个函数,如果它在productionenv 上,它将为图像 url 添加一个前缀。

export function getAssetUrl(path: string) {
  return process.env.NODE_ENV === 'production' ? `${MAIN_URL}${path}` : path;
}

但是对于字体,我不太确定推荐的方式是什么。目前我的自定义字体styles/globals.css如下:

@font-face {
  font-family: 'MyCustomFont';
  font-style: normal;
  font-weight: 400;
  src: url('/fonts/MyCustomFont-Regular.ttf') format('truetype');
  font-display: swap;
}

@font-face {
  font-family: 'MyCustomFont';
  font-style: normal;
  font-weight: 700;
  src: url('/fonts/MyCustomFont-Bold.ttf') format('truetype');
  font-display: swap;
}

@font-face {
  font-family: 'MyCustomFont';
  font-style: italic;
  font-weight: 700;
  src: url('/fonts/MyCustomFont-BoldItalic.ttf') format('truetype');
  font-display: swap;
}

因此,在部署时,字体将不在根公用文件夹中,而是在example.com/my-next-js-app/fonts/MyCustomFont-xxx.ttf.

标签: javascriptcssreactjsnext.js

解决方案


推荐阅读