简体   繁体   English

如何使用 Angular-Cli“要求”SASS?

[英]How can I `require` SASS with Angular-Cli?

According to this , require can be used at the component level to split css into chunks.根据require可以在组件级别被用于CSS分成块。

However, the following works when using ng serve , but not when using ng serve --prod .但是,以下在使用ng serve ,但在使用ng serve --prodng serve --prod

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [require('./app.component.scss')],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent {
  title = 'my-app';
}

The CSS is not loaded in at all when given the prod flag.给定 prod 标志时,根本不会加载 CSS。 Is this a bug, or is there something that I'm missing?这是一个错误,还是我遗漏了什么?

These are the default flags that are set for ng serve and ng serve --prod respectively这些是分别为 ng serve 和 ng serve --prod 设置的默认标志

Flag                 --dev      --prod
--aot                false      true
--environment        dev        prod
--output-hashing     media      all
--sourcemaps         true       false
--extract-css        false      true

Using ng serve --prod --extract-css=false could do the trick assuming the extract-css= true is what's breaking your require on the css file使用 ng serve --prod --extract-css=false 可以做到这一点,假设 extract-css= true 是破坏了你对 css 文件的要求

So for anyone who might stumble upon this, I found that require just doesn't work properly without creating a manual Webpack configuration.因此,对于可能偶然发现此问题的任何人,我发现如果不创建手动 Webpack 配置, require就无法正常工作。 I didn't want to do that, so here's what I did instead:我不想这样做,所以这是我所做的:

Under styles in the Angular-CLI JSON, I added my SASS with a defined input and output, so that the Angular-CLI would still compile my SASS, but not bundle it.在 Angular-CLI JSON 的styles下,我添加了具有定义输入和输出的 SASS,这样 Angular-CLI 仍会编译我的 SASS,但不会捆绑它。

"styles": [
  {
    "input": "scss/style.scss",
    "output": "assets/style/style"
  }
]

Then I went old school and simply added a link tag to the output csss in my index.html.然后我回到了老学校,只是在我的 index.html 的输出 csss 中添加了一个链接标签。

I found that since the prod build adds hashing to the CSS, the link wouldn't work, so I also needed to build with Output Hashing set to media only so that i could just link to the CSS.我发现由于 prod 构建向 CSS 添加了散列,因此链接不起作用,因此我还需要将输出散列设置为仅媒体进行构建,以便我可以链接到 CSS。

ng build --prod --output-hashing=media

Thanks to @Kevin for pointing out what flags are set with the prod flag.感谢@Kevin 指出使用 prod 标志设置了哪些标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM