Angular 4 organizes its styles in a way that can make you fall in love again. Angular simulates encapsulation by default on every component, utilizing the power of attribute selectors. In short, adds unique attribute on every angular component’s selector.
I love to have variables in separate files like colors, mixins and so on. But found myself I can use them only if they are added globally or added separately in every component that I needed.
In the first case we can import all partials in the global styles.sass file, but we might not want that, it goes against the encapsulation philosophy and there is no autocomplete.
In the second case, adding every time needed @imports with the correct path was not practical and honestly it felt messy.
The struggle continues
I found the holy grail with node-sass and its automated way to add all @imports. But unfortunately, having the opportunity to set different options for Sass, Less, Stylus, etc is not supported by Angular Cli as “it would be practically unmaintainable”.
The solution is probably the best from both worlds. It’s almost practical, but maintainable by the Angular Cli guys.
The trick is to use stylePreprocessorOptions in the angular-cli.json.
First I’ve moved global styles.scss in a new folder called style. There created partials like _colors.scss, _mixins.scss, etc. To import for example _colors.scss in some component, we need to open the component’s Sass file and add the following line:
As I said it’s not the best solution, but nevertheless it’s easy.
To add just that line, skipping the underscore, the path and the extension, we need to set our stylePreprocessorOptions in angular-cli.json.
In my case:
If we want to include colors and mixins there will be two lines of code:
To have autocomplete with VSCode we need to install extension called SCSS IntelliSense.
Finally, we’ve ended with a way to use our variables and have autocomplete.
Here is a newly generated angular-cli.json file will added Sass and stylePreprocessorOptions: