如何让我的 NextJS 应用接受 otf 和 ttf 字体?

Web*_*man 9 next.js

我正在使用 NextJS,当我构建我的应用程序时,我的控制台返回给我:

ModuleParseError: Module parse failed: Unexpected character '' (1:0) 你可能需要一个合适的加载器来处理这个文件类型。

我想知道出了什么问题,因为我已经构建了一个自定义 webpack 的配置。

这是我的 next.config.js:

module.exports={ 
  exportPathMap: () => ({ 
      "/": {page: '/'}
  })
}

const config = { 
  cssModules: true,
  module:{ 
    rules:[ 
      {
        test:/\.(png|jpg|woff|svg|eot|ttf|woff2|otf)$/,
        loader:'url-loader?limit=8192&name=images/[name].[ext]'

        }
    ]
  }

}

// config.module.rules.push(

//   );

const   withCss =   require('@zeit/next-css');
const   withImages  =   require('next-images');
module.exports  =   withImages(withCss(config));
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用 css 来启动我的应用程序,该 css 精确了我的字体格式 vie 的性质format("opentype"),但没有它,但两者都失败了:

@font-face {
    font-family: Moonlight;
    src: url(../assets/choiceFonts/Moonlights_on_the_Beach.ttf);
}

@font-face {
    font-family: Nenuphar;
    src: url(../assets/choiceFonts/Nenuphar_of_Venus.otf) format("opentype");
}


@font-face {
    font-family: Prida;
    src: url(../assets/choiceFonts/Prida01.otf) format("opentype");
}
Run Code Online (Sandbox Code Playgroud)

任何提示都会很棒,谢谢

Reh*_*tar 21

对于仍在此问题中受苦的其他人

在 next 的最新版本中,您将所有静态资产存储在/public项目根目录下的目录中。在该目录中,将所有字体文件存储在一个目录中/fonts

然后:

@font-face {
  font-family: 'font-name';
  src: url('/fonts/font-name.ttf'); // pattern: /directoryName/file.extension
 }

/* In your css file where you want to use the font */
.element { 
 font-family: 'font-name';
}
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止最好的答案,不需要额外的依赖项,不需要配置文件。只是CSS。 (2认同)
  • 所以对我来说,我必须在 src: url("/path") 之后删除 'format("ttf")' 并且它有效,因此由于某种原因指定格式阻止了 next.js 渲染字体! (2认同)

Sal*_*rma 8

我使用了以下依赖项

npm 安装下一个字体

我的next.config.js看起来像这样

 const withFonts = require('next-fonts');

 module.exports = withFonts({
    enableSvg: true,
    webpack(config, options) {
      return config;
    }
 }); 
Run Code Online (Sandbox Code Playgroud)