Tutorial

Using Sass with the Angular CLI

Updated on September 15, 2020
    author

    Chris on Code

    Using Sass with the Angular CLI

    One of the first things you’ll usually do in a project is to bring in Sass to make working with CSS easier.

    Angular CLI Home Page

    When working with the Angular CLI, the default stylesheets have the .css extension.

    <div class=“notification is-info m-b-md”>Related Video Course: <a href=“https://scotch.io/courses/working-with-the-angular-cli”>Working with the Angular CLI</a></div>

    Let’s explore how we can easily bring in Sass to our Angular CLI projects.

    Sass Home Page

    If you want a quick intro into the Angular CLI, check out the official docs and our Use the Angular CLI For Faster Angular v2+ Projects.

    Starting an Angular CLI Project with Sass

    Normally, when we run ng new my-app, our app will have .css files. To get the CLI to generate .scss files (or .sass/.less) is an easy matter.

    Create a new project with Sass with the following:

    ng new my-sassy-app --style=scss
    

    You can also set the --style flag with the following:

    • --style=scss
    • --style=sass
    • --style=less

    Converting a Current App to Sass

    If you’ve already created your Angular CLI app with the default .css files, it will take a bit more work to convert it over. You can tell Angular to start processing Sass files with the following command:

    ng set defaults.styleExt scss
    

    This will go ahead and tell the Angular CLI to start processing .scss files. If you want to peek under the hood at what this command did, check out the Angular CLI config file: .angular-cli.json.

    You’ll find the new config line at the bottom of the file:

    "defaults": {
      "styleExt": "scss",
      "component": {
      }
    }
    

    Changing the CSS Files to Sass

    The Angular CLI will start processing Sass files now. However, it doesn’t go through the process of converting your already existing .css files to .scss files. You’ll have to make the conversion manually.

    Using Sass Imports

    I personally like creating Sass files for project variables and for project mixins. This way, we can bring in any variables/mixins we’ll need quickly and easily.

    For instance, let’s create a brand new CLI app:

    ng new my-sassy-app --style=scss
    

    Next, we’ll create the following files:

    |- src/
        |- sass/
            |- _variables.scss
            |- _mixins.scss
            |- styles.scss
    

    To start using these new Sass files, we’ll import the _variables.scss and _mixins.scss into the main styles.scss.

    // src/sass/styles.scss
    
    @import './variables';
    @import './mixins';
    

    The last step is to update our .angular-cli.json config to use this new src/sass/styles.scss instead of the src/styles.scss. In our .angular-cli.json file, just change the following line to point to the right styles.scss.

    "styles": [
      "sass/styles.scss"
    ],
    

    I like separating out our Sass into its own folder because it allows us to create a more robust Sass foundation. I personally lean towards the Sass 7-1 Pattern.

    Now when we start up our app, these new Sass files will be used!

    Importing Sass Files Into Angular Components

    We have new _variables.scss and _mixins.scss files that we will probably want to use in our components. In other projects, you may be used to having access to your Sass variables in all locations since your Sass is compiled by a task runner.

    In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component’s Sass file, you’ll need to import the _variables.scss file.

    One way to do this is to @import with a relative path from the component. This may not scale if you have many nested folders or eventually move files around.

    The CLI provides an easy way to import Sass files using the ~.

    No matter what component Sass file we’re in, we can do an import like so:

    // src/app/app.component.scss
    
    @import '~sass/variables';
    
    // now we can use those variables!
    

    The tilde (~) will tell Sass to look in the src/ folder and is a quick shortcut to importing Sass files.

    Sass Include Paths

    In addition to using the ~, we can specify the includePaths configuration when working with the CLI. To tell Sass to look in certain folders, add the config lines to .angular-cli.json like in the app object next to the styles setting.

    <div class=“notification is-info”>This is the recommended way to use Sass files in an Angular CLI app. It is better to be more explicit about where our files come from. We can do that with stylePreprocessorOptions.includePaths.</div>

    "styles": [
      "styles.scss"
    ],
    "stylePreprocessorOptions": {
      "includePaths": [
        "../node_modules/bootstrap/scss"
      ]
    },
    

    Using Bootstrap Sass Files

    Another scenario we’ll need to do often is to import third party libraries and their Sass files.

    We’ll bring in Bootstrap and see how we can import the Sass files into our project. This is good since we can pick and choose what parts of Bootstrap we want to use. We can also import the Bootstrap mixins and use them in our own projects.

    To get us started, install bootstrap:

    npm install --save bootstrap
    

    Note: We’re using the 4.0 beta because 4.0 is built with Sass and gives the proper .scss files.

    Adding Bootstrap CSS File

    Now that we have Bootstrap, let’s look at how we can include the basic CSS file. This is an easy process by adding the bootstrap.css file to our .angular-cli.json config:

    "styles": [
      "../node_modules/bootstrap/dist/css/bootstrap.css",
      "sass/styles.scss"
    ],
    

    Note: We’re using the .. because the CLI starts looking from within the src/ folder. We had to go up one folder to get to the node_modules folder.

    While we can import the Bootstrap CSS this way, this doesn’t let us import just sections of Bootstrap or use the Sass variables/mixins that Bootstrap provides.

    Let’s look at how we can use the Bootstrap Sass files instead of the CSS file.

    Adding Bootstrap Sass Files

    Let’s cut down the number of CSS rules that we use in our app. Let’s look at all the Sass files that Bootstrap uses:

    /*!
     * Bootstrap v4.0.0-beta (https://getbootstrap.com)
     * Copyright 2011-2017 The Bootstrap Authors
     * Copyright 2011-2017 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     */
    
    @import "functions";
    @import "variables";
    @import "mixins";
    @import "print";
    @import "reboot";
    @import "type";
    @import "images";
    @import "code";
    @import "grid";
    @import "tables";
    @import "forms";
    @import "buttons";
    @import "transitions";
    @import "dropdown";
    @import "button-group";
    @import "input-group";
    @import "custom-forms";
    @import "nav";
    @import "navbar";
    @import "card";
    @import "breadcrumb";
    @import "pagination";
    @import "badge";
    @import "jumbotron";
    @import "alert";
    @import "progress";
    @import "media";
    @import "list-group";
    @import "close";
    @import "modal";
    @import "tooltip";
    @import "popover";
    @import "carousel";
    @import "utilities";
    

    That’s a lot of tools that you may not use in your own project.

    Inside our src/sass/styles.scss file, let’s import only the Bootstrap files we’ll need. Just like we imported Sass files from the src folder using the tilde (~), the tilde will also look into the node_modules folder.

    While we could use the tilde, since we already added Bootstrap to our include_paths in the stylePreprocessorOptions section of our .angular-cli.json:

    "styles": [
      "styles.scss"
    ],
    "stylePreprocessorOptions": {
      "includePaths": [
        "../node_modules/bootstrap/scss"
      ]
    },
    

    We can do the following to only get the Bootstrap base tools:

    // src/sass/styles.scss
    
    @import 
      'functions',
      'variables',
      'mixins',
      'print',
      'reboot',
      'type';
    

    Conclusion

    The tilde (~) and the ability to add paths to stylePreprocessorOptions.includePaths makes importing Sass files in the Angular CLI super easy! Hope this quick tip was helpful in your Angular journey. Thanks for reading.

    While it is easy to use the ~ in quick situations, I recommend using the includePaths method to be explicit about the exact folders where your .scss files live.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about our products

    About the authors
    Default avatar
    Chris on Code

    author

    While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Featured on Community

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more