How to use SASS for components style in Angular 2?

2019-06-16 16:46发布

问题:

In Angular 2 when we define a component we can specify a styleUrls property to the decorator which points to a set of stylesheets to be applied to the component:

@Component({
    selector: 'the-app'
    templateUrl: 'templateFile.html',
    styleUrls: ['componentStyles.css', 'moreComponentStyles.css']
})
export class TheAppComponent {}

Now, what if I want to write these styles with SASS?

I know I would need to use Gulp or Grunt to transpile the SCSS stylesheets to plain CSS. But this makes me confused on how we would correctly point Angular to the correct stylesheets.

How could I organize this workflow of using SASS with Gulp/Grunt together with Angular 2? How to use SASS to write the Angular 2 components styles?

回答1:

After following this wiki, I got some Error: Uncaught (in promise): Expected 'styles' to be an array of strings which I resolved using this answer.

Final solution is here:

home.component.ts:

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

@Component({
  selector: 'home',
  template: require('./home.component.html'),
  styles: [ String(require('./home.component.scss')) ]
})

export class HomeComponent { }

webpack.conf.js: (part of it)

  {
    test: /\.(css|scss)$/,
    loaders: [
      'style',
      'css',
      'sass',
      'postcss'
    ]
  },


回答2:

You can use .scss in Component like this-

styles: [require('normalize.css'), require('./app.scss')],

See if this helps.



回答3:

I'm using it this way:

import {Component} from "@angular/core";

// for webpack
require('./footer.scss');

@Component({
     selector: 'footer',
     templateUrl: 'app/footer/footer.html',
    styleUrls: ['app/footer/footer.scss'],
})
export class FooterComponent {}


回答4:

Command line inside project folder where your existing package.json is: npm install node-sass sass-loader raw-loader --save-dev

In webpack.common.js, search for "rules:" and add this object to the end of the rules array (don't forget to add a comma to the end of the previous object):

{
  test: /\.scss$/,
  exclude: /node_modules/,
  loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
}

Then in your component:

@Component({
  styleUrls: ['./filename.scss'],
})