角度4多个全局样式与延迟加载

时间:2017-09-18 20:43:10

标签: angular angular-cli

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

现在我运行命令

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

它为bootstrap生成以下输出

  

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

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

现在,我如何在网站中使用bootstrapBundle或bootstrap chunk?

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

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

请帮忙。

感谢。

1 个答案:

答案 0 :(得分:4)

我在@Kuncevic的帮助下找到了我的问题的解决方案,他指的是这个

  

Lazy load application theme styles with Angular CLI

现在直到这一点,将生成css文件,如果我们通过

将它们添加到index.html
<link href='yourstyle.bundle.css' rel='stylesheet'/>

然后它会在第一次请求时急切地加载。

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

解。

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

    <强> app.component.html

    <div *ngIf="stylesLoaded">
      <link rel="stylesheet" href="/bootstrap.cf320d25069acd157990.bundle.css">
    </div>
    
    1. isLoaded 属性添加到 app.component.ts
    2. app.component.ts 中实施 AfterViewChecked 。有关详细信息Check Life cycle Hooks
    3.   

      <强> app.component.ts

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

      现在,一旦您的视图被渲染, AfterViewChecked 将被触发并使 stylesLoaded 变为 true ,这将启用 app.component.html 并开始加载它们。

        

      因此延迟加载:)

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

      希望能帮助某人。快乐的编码

相关问题