8

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?

user1620696
  • 10,825
  • 13
  • 60
  • 81
  • If by chance you are using the [angular-cli](https://cli.angular.io/) all you need to do is rename the file name and leave all other references alone and the angular-cli will take care of the rest – Jarod Moser Jul 11 '16 at 18:44
  • 1
    I found how to make this work. Just read my answer below :) – MaximeBernard Jul 13 '16 at 10:40

4 Answers4

3

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'
    ]
  },
Community
  • 1
  • 1
MaximeBernard
  • 1,090
  • 1
  • 19
  • 33
  • could you pls share webpack.conf.js – Peter Nov 03 '16 at 13:14
  • when i use :styles: [ String(require('./home.component.scss')) ] then it starts looking for home.component.scss.js file. hence give 404 not found. Why does it looks for scss.js file? – Peter Nov 04 '16 at 02:29
0

You can use .scss in Component like this-

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

See if this helps.

Sanket
  • 19,295
  • 10
  • 71
  • 82
0

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 {}
Angel M.
  • 2,692
  • 2
  • 32
  • 43
0

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'],
})