How to use Angular 4 with SASS

celsomtrindade picture celsomtrindade · Jun 22, 2017 · Viewed 21.7k times · Source

I'm starting my first project using Angular4 and sass and I'm trying to figure it out how to work with sass the proper way. I'm using angular-cli and already set the default style to use scss syntax. I also already defined the compilation, etc.

However I saw that we have an option styleUrls on the component, where in some cases we define styles used only in that component.

The problem is, when I set a scss file in that component it's not generating it's own .css file neither being included in the main .css file, generated from the root project.

So basically I have a project structure like this:

app
    app.module.ts
    app.routing.ts
    home
        home.component.ts
        home.html
        _home.scss
    client
        client.component.ts
        client.html
        _client.scss
scss
    _imports.scss
    colors
        _colors.scss
    ui
        _button.scss
        _table.scss
    //.. more folder and files
styles.scss
index.html

And I'd like to be able to set the main css style within the styles.scss file, which will be inserted into the index.html file later, on the build process. But also be able to generate a single css file for each component I have, e.g. home and client, and only use those css styles within their own component.

Is it possible to do it? I've tried to do it and I didn't find any other resource about this!

Answer

Obsidian Age picture Obsidian Age · Jun 22, 2017

What you are looking for is the import directive:

@import "styles.scss";  
@import "css/styles.scss";  
@import url("http://example.com/css/styles.scss");

This imports the CSS from the other CSS files into the main CSS file, appending the contents of each file to the main file based on the order that you choose to insert them.

Note that you do not need the .scss file extension, as SASS will handle that automatically, and you can simply import with @import "file". And you also don't need to specify each file with an independent import, as you can combine them all in a single import:

@import "styles.scss", "css/styles.scss", url("http://example.com/css/styles.scss");

You can also do nested imports by specifying the @import within a selector:

.global-nav {  
  @import "nav-bkgd";
}

Hope this helps! :)