具有延迟加载的 angular 4 多个全局样式

Riy*_*Riy 6 angular-cli angular

到目前为止,我正在使用angular-cli 1.3.2 版构建一个 angular 4 应用程序。我在文档中读到我们可以在https://github.com/angular/angular-cli/wiki/stories-global-styles使用全局样式和延迟加载。

现在当我运行命令时

ng build --prod -vc -nc --build-optimizer
Run Code Online (Sandbox Code Playgroud)

它为引导程序生成以下输出

块 {bootstrapBundle} bootstrapBundle.cf320d25069acd157990.bundle.css (bootstrapBundle) 96.9 kB {inline} [initial]

根据我的理解,这个 css 应该应用于网站,但是,当我看到该网站时,它没有应用任何引导 css。

现在,如何在站点中使用 bootstrapBundle 或 bootstrap 块?

这是我的angular-cli.json样式配置

"styles": [
      "styles.scss"
       {
         "input": "./assets/smartadmin/bootstrap.scss",
         "lazy": true,
         "output":"bootstrapBundle"
       },
    ],
Run Code Online (Sandbox Code Playgroud)

请帮忙。

谢谢。

Riy*_*Riy 6

在@Kuncevic 的帮助下,我找到了解决我的问题的方法,@Kuncevic 向我指出了这一点

使用 Angular CLI 延迟加载应用程序主题样式

现在直到这一点,将生成 css 文件,如果我们通过以下方式将它们添加到 index.html

<link href='yourstyle.bundle.css' rel='stylesheet'/>
Run Code Online (Sandbox Code Playgroud)

然后它将在第一个请求时急切地加载。

但问题是,我真的很想懒惰地加载它们并将它们应用到我的网站上


解决方案。

  1. 提取出文章中提到的css
  2. 添加了对app.component.html 的样式引用,因为这将是一个根组件,因此我在此添加了它。

应用程序组件.html

<div *ngIf="stylesLoaded">
  <link rel="stylesheet" href="/bootstrap.cf320d25069acd157990.bundle.css">
</div>
Run Code Online (Sandbox Code Playgroud)
  1. app.component.ts添加isLoaded属性
  2. 已实施AfterViewCheckedapp.component.ts。有关详细信息,请检查生命周期挂钩

app.component.ts

export class AppComponent implements AfterViewChecked {
  stylesLoaded: boolean = false;
  
  constructor() {}

  ngAfterViewChecked() {
    this.stylesLoaded = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,一旦您的视图呈现,AfterViewChecked将被触发并使styleLoadedtrue,这将启用app.component.html 中的样式链接并开始加载它们。

因此懒加载:)

以类似的方式,您可以加载 JS 模块。

希望这会帮助某人。快乐编码

  • 自从您在索引文件中添加带有散列的 css 包作为链接后,它是如何工作的?每次应用程序构建时,哈希值都会发生变化,那么您的链接将是错误的,并且捆绑包获取将是旧链接。 (2认同)