简体   繁体   中英

How can I `require` SASS with Angular-Cli?

According to this , require can be used at the component level to split css into chunks.

However, the following works when using ng serve , but not when using ng 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. 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

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

So for anyone who might stumble upon this, I found that require just doesn't work properly without creating a manual Webpack configuration. 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.

"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.

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.

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

Thanks to @Kevin for pointing out what flags are set with the prod flag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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