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?

2
  • If by chance you are using the angular-cli 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 Commented Jul 11, 2016 at 18:44
  • 1
    I found how to make this work. Just read my answer below :) Commented Jul 13, 2016 at 10:40

4 Answers 4

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'
    ]
  },
Sign up to request clarification or add additional context in comments.

2 Comments

could you pls share webpack.conf.js
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?
0

You can use .scss in Component like this-

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

See if this helps.

Comments

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 {}

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.