在 Angular 项目中包含 Material Icons 的最佳实践、tree-shakeable 方式是什么?

Pet*_*xey 6 angular-material google-material-icons angular

我一直在尝试将一些 Material 图标包含到 Angular 项目中,但每次我都会发现一些特殊之处。

1.所有图标导入后图标才有效

以下方法成功地将所有图标包含到项目中:

<!-- index.html -->
<head>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  ...
</head
Run Code Online (Sandbox Code Playgroud)
// app.module
import { MatIconModule } from '@angular/material/icon'
...
@NgModule({
  imports: [
    MatIconModule
  ]
})

Run Code Online (Sandbox Code Playgroud)
<!-- component.html -->
<mat-icon aria-hidden="false" aria-label="Example home icon">home</mat-icon>
Run Code Online (Sandbox Code Playgroud)

该图标已包含并按预期显示在页面中。然而,由于我从未明确导入过我正在使用的一个图标,所以我必须假设整个模块已被导入。对于一个图标来说,有很多代码,我更愿意将它们一一导入。

2.使用MatIconRegistry将它们一一导入会抛出错误

由于包含整个模块会让我的包变得臃肿,所以我尝试使用MatIconRegistry. 我的理解是,这应该允许我一一注册图标

// app.module
import { MatIconModule } from '@angular/material/icon'
...
@NgModule({
  imports: [
    MatIconModule
  ]
})
Run Code Online (Sandbox Code Playgroud)
// my.component.ts

import { DomSanitizer } from '@angular/platform-browser'
import { MatIconRegistry } from '@angular/material/icon'
...
constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
  iconRegistry.addSvgIcon(
    'home',
      sanitizer.bypassSecurityTrustResourceUrl('assets/img/examples/home-icon.svg')
  )
}
Run Code Online (Sandbox Code Playgroud)
<!-- my.component.html -->
<mat-icon svgIcon="home" aria-hidden="false" aria-label="Home icon"></mat-icon>
Run Code Online (Sandbox Code Playgroud)

但这有两个问题。首先,我不知道该资产文件来自哪里,因为它当前不存在于我的文件系统中。第二个是编译器无论如何都不喜欢它:

ERROR in src/app/modules/platform/entries/entries.component.html:8:5 - error NG8001: 'mat-icon' is not a known element:
1. If 'mat-icon' is an Angular component, then verify that it is part of this module.
Run Code Online (Sandbox Code Playgroud)

所以第一种方法有效,但我无法使第二种方法有效。我担心/假设第一种方法意味着导入整个图标集,使其效率非常低。