我使用的是Angular 2+和Angular CLI。

我如何添加字体awesome到我的项目?


当前回答

从https://github.com/AngularClass/angular-starter开始,在测试了许多不同的配置组合之后,下面是我如何让它与AoT一起工作的。

我已经说过很多次了,在我的app.component.scss中:

$fa-font-path: "~font-awesome/fonts" !default;
@import "~font-awesome/scss/font-awesome";

然后在webpack.config.js中(实际上是启动包中的webpack.comm .js):

在插件部分:

new CopyWebpackPlugin([
    { from: 'src/assets', to: 'assets' },
    { from: 'src/meta'},
    { from: 'node_modules/font-awesome/fonts', to: 'assets/fonts/' }
]),

在规则部分:

,
{
    test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
    use: 'file-loader?name=/assets/fonts/[name].[ext]'
}

其他回答

如果你使用的是SASS,你可以通过npm安装它

npm install font-awesome --save

然后导入到你的/src/styles中。scss:

$fa-font-path: "../node_modules/font-awesome/fonts";
@import "../node_modules/font-awesome/scss/font-awesome.scss";

提示:只要有可能,避免混淆angular-cli的基础设施。;)

上面的答案有点过时了,有一种稍微简单的方法。

通过NPM安装 NPM install font-awesome——保存 在你的style.css中: @ import“~ font-awesome / css / font-awesome.css”; 或者用你的风格。 $ fa-font-path:“~ font-awesome /字体”; @ import ' ~ font-awesome / scss / font-awesome '; 编辑:如注释中所述,字体行必须在新版本上更改为$fa-font-path: "../../../node_modules/font-awesome/fonts";

使用~将使sass查找node_module。这样做比相对路径更好。原因是,如果你在npm上上传了一个组件,然后在组件scss中导入了font-awesome,那么它将使用~正常工作,而不是使用相对路径,因为相对路径在那一点上是错误的。

此方法适用于任何包含css的npm模块。它也适用于scss。然而,如果你导入css到你的样式。SCSS是行不通的(也许反之亦然)。原因如下

公认的答案已经过时了。

棱角分明,棱角分明

安装FontAwesome NPM install @fortawesome/ fontawessome -free——保存 在angular上注册它。样式下的Json “node_modules / @fortawesome / fontawesome-free / css / all.min.css” 在您的应用程序中使用它

在Angular 2.0最终版发布之后,Angular2 CLI项目的结构已经改变了——你不需要任何供应商文件,不需要system.js——只需要webpack。所以你会:

npm install font-awesome --save In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below: "apps": [ { "root": "src", "outDir": "dist", .... "styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.css", "../node_modules/font-awesome/css/font-awesome.css" // -here webpack will automatically build a link css element out of this!? ], ... } ] ], In more recent versions of Angular, use the angular.json file instead, without the ../. For example, use "node_modules/font-awesome/css/font-awesome.css". Place some font-awesome icons in any html file you want: <i class="fa fa-american-sign-language-interpreting fa-5x" aria-hidden="true"> </i> Stop the application Ctrl + c then re-run the app using ng serve because the watchers are only for the src folder and angular-cli.json is not observed for changes. Enjoy your awesome icons!

这里有很多好的答案。但如果你尝试了所有这些,仍然得到方形而不是方正的图标,检查你的css规则。在我的例子中,我有以下规则:

* {
  font-family: Roboto-Light, Roboto, 'Helvetica Neue', sans-serif !important;
}

它覆盖了一些字体。只是将* selector替换为body解决了我的问题:

body {
  font-family: Roboto-Light, Roboto, 'Helvetica Neue', sans-serif !important;
}