Import SCSS in a shorter way in Angular

I was working on a Angular project and for the styling of the application we used the SCSS preprocessor. We organized our styles across multiple SCSS files. Some of these files held essential styling components like variables and mixins, which were frequently imported.

In case we wanted to use a mixin or variable in another SCSS file, we needed to import the necessary file. Therefore we use the @use statement with the path to the file.

@use '../../core/vars';

Although this works, the path can become very large, expecially when you want to import SCSS in an stylesheet of an Angular component. Sometimes we got something like this:

@use '../../../../../core/mixins';

There must be a way to write this import cleaner right? Luckily there is!

Configure stylePreprocessorOptions in angular.json

In the angular.js file, in the builder configuration for the project, you can configure the stylePreprocessorOptions options tag. This tag has a includePaths array property in which you can define directories which contains (S)CSS files. These paths are called base paths and the compiler will look into these paths when searching for an (S)CSS file which is imported in a SCSS file.

{
  "projects": {
    "your-app": {
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:application",
          "options": {
            "stylePreprocessorOptions": {
              "includePaths": [
                "src/style",
                "src/other"
              ]
            }
          }
        }
      }
    }
  }
}

Add the same tag configuration to the test builder to prevent errors about non-existing (S)CSS file paths when running unit tests.

Result

This configuration change helps in creating a shorter path when importing a SCSS file:

@use 'core/vars';
/* Instead of @use '../../../../../core/vars'; */

References

Angular.dev reference about style and scripts configuration