0

对于我的服务器,我希望启用字体的动态加载。服务器使用nestjs运行

我将 .woff 文件托管在服务器上名为“fonts”的目录中。

@font-face 是在 html 头部的样式标记中动态构建的(根据所需的字体)。

但是,当我将 url 设置为文件的路径时,如下所示:

@font-face {
      font-family: Roboto;
      src: url(fonts/roboto-v29-latin-regular.woff);
    }

然后 GET 以 404 not found 结束。

当我简单地使用文件名时:

@font-face {
          font-family: Roboto;
          src: url(roboto-v29-latin-regular.woff);
        }

然后返回一个空对象 {}

将不胜感激您的见解!

4

2 回答 2

1

问题是nestjs 没有提供字体文件。我必须使用 ServeStaticModule.forRoot 从 appModule 静态地为它们提供服务:

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'fonts'),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

然后将我的字体文件夹复制到 dist 目录。这解决了问题。

于 2021-11-22T13:13:44.997 回答
0

有几个解决方案可能是潜在的修复,这取决于您如何处理 CSS 文件。

如果文件夹中有roboto-v29-latin-regular.woff文件fonts,则意味着 CSS 会尝试在本地目录中查找路径。./要在本地目录中查找某些内容,请在斜杠 ( )前面使用点。因此,如果我们有以下目录:

/fonts
 -roboto-v29-latin-regular.woff
styles.css

那么 for 的路径roboto-v29-latin-regular.woff将是./fonts/roboto-v29-latin-regular.woff,它将导致以下字体:

@font-face {
  font-family: Roboto;
  src: url(./fonts/roboto-v29-latin-regular.woff);
}

这就是您可以轻松访问当前级别以上的本地或目录的方式。读这个

但是,如果您以不同的方式处理 CSS,则只需/在文件夹前面提供一个,fonts这将是从本地实例服务器 URL 获取字体的结果:

/* Imagine your URL to be: http://localhost:3000/fonts/roboto-v29-latin-regular.woff */

@font-face {
  font-family: Roboto;
  src: url(/fonts/roboto-v29-latin-regular.woff);
}

同样,如果上述解决方案都不起作用,只需放置字体外部 URL(来自谷歌字体等)


@font-face {
  font-family: Roboto;
  src: url(<EXTERNAL_URL>);
}
于 2021-11-22T12:34:48.780 回答