如何在Angular 6中添加Google字体库?

7
我已经在 Angular 项目的 styles.scss 文件中添加了 Google 字体链接。
@import url('https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700');

但是它已经可以使用Angular CLI命令 ng serve 工作,但是尝试使用命令ng build --prod --base-href来构建并部署项目时,发现了问题。

问题在于它“无法导入谷歌字体”。

我在谷歌上研究了这个问题,但是没有找到一个好的解决方案。

我想知道如何在Angular项目中应用谷歌字体?


我总是将它们链接到index.html的头部,从未遇到过问题? - Brad Axe
如果您在 index.html 文件的 <header> 中添加链接,它应该可以正常工作。但是,在使用 --base-href 构建时可能会出现 URL 或路径引用错误。 - micronyks
你可以先在本地构建并运行你的项目。关于如何使用命令 ng build --prod --base-href,请参考以下步骤: - RedAnz
清除浏览器缓存和应用数据。我刚刚测试了使用和不使用 --base-href /test/,都可以正常工作。 - Brad Axe
这里非常详细地解释了 https://golb.hplar.ch/2019/06/google-fonts-download.html - Ravindra
显示剩余3条评论
3个回答

8

这是在Angular 2、4、5、6、7等版本中本地使用Google字体的最佳方法,首先下载Google字体并将其放入assets文件夹中,然后按照需求使用。

在angular.json中调用src/assets中的文件。

"assets": [
    "src/assets"
 ],

在 CSS 文件顶部添加此 font-face。
@font-face {
  font-family: 'Montserrat';
  src: url(/assets/Montserrat/Montserrat-Light.ttf) format("truetype");
  font-weight:300;
}

最后,根据您的需求使用它,如下所示:

body{
 font-family: 'Montserrat', sans-serif;
}

1
这是一个方便的小工具,可以从Google中选择您喜欢的字体。链接为:https://google-webfonts-helper.herokuapp.com/fonts - FuzzyTemper

5
如果你想在你的Angular应用中包含自己版本的谷歌Roboto字体,可以通过以下步骤实现:
1. 使用命令 `npm install roboto-fontface` 安装Roboto字体。 2. 在 `angular.json` 文件中将字体文件添加到样式列表中,例如:
"styles": [              
          "node_modules/roboto-fontface/css/roboto/roboto-fontface.css"
        ],

3
将其放置在styles.scss文件中:@import "~roboto-fontface/css/roboto/roboto-fontface.css";。请注意,翻译过程中不会添加解释或其他信息。 - Kyle Krzeski
这可以与任何Google字体一起使用吗? - JoeCool-Avismón

1
尝试像这样做:
index.html 中。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>title</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">

</head>

<body>
    <app-root>
        Loading...
    </app-root>
</body>
</html>

你已经按照上面的指示添加了吗? - Akj
你的代码和我的代码一样,但有一个不同之处,那就是 <base href="">。当实现项目时,如果使用 <base href="/">,则该项目将无法正常工作。 - RedAnz
你能否移除基础部分,只使用简单链接呢?这对我来说运行良好。 - Akj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接