【问题标题】:angular 4 multiple global styles with lazy loading角度 4 多个全局样式,延迟加载
【发布时间】:2018-02-27 11:58:23
【问题描述】:

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

现在当我运行命令时

ng build --prod -vc -nc --build-optimizer

它为引导生成以下输出

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

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

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

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

"styles": [
      "styles.scss"
       {
         "input": "./assets/smartadmin/bootstrap.scss",
         "lazy": true,
         "output":"bootstrapBundle"
       },
    ],

请帮忙。

谢谢。

【问题讨论】:

标签: angular angular-cli


【解决方案1】:

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

Lazy load application theme styles with Angular CLI

到目前为止,css 文件将被生成,如果我们将它们添加到 index.html 中

<link href='yourstyle.bundle.css' rel='stylesheet'/>

然后它将在第一次请求时立即加载。

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


解决方案。

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

app.component.html

<div *ngIf="stylesLoaded">
  <link rel="stylesheet" href="/bootstrap.cf320d25069acd157990.bundle.css">
</div>
  1. app.component.ts 添加了 isLoaded 属性
  2. app.component.ts 中实现了 AfterViewChecked。详情Check Life cycle Hooks

app.component.ts

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

  ngAfterViewChecked() {
    this.stylesLoaded = true;
  }
}

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

因此延迟加载:)

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

希望这对某人有所帮助。快乐编码

【讨论】:

  • 自从您在索引文件中添加带有散列的 css 包作为链接后,它如何工作?每次构建应用程序时,哈希值都会发生变化,那么您的链接将是错误的,并且捆绑包获取将是旧的。
  • 提取的 CSS 包不再在较新版本的 Angular(绝对是 v10)中进行哈希处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2018-12-15
相关资源
最近更新 更多