Angular 2, Webpack SASS

19 September 2016By Rich @Black Sand Solutions
  • Angular

I've recently started a new project using the Angular 2 Webpack Starter. It's a good starting point, but is not set up to use SASS partials.

Angular 2, Webpack & SASS

What I want is to have some common partials that are injected and compiled as required.

I've spent quite a bit of time trawling through Google and come up with the following. It's not perfect by any means, but it gets the job done.

First up, here is the file tree, note the additions.

The partials are in a folder of their own. There is also a global sass file at the app level.

webpack.common.js

A SASS loader section is added to the config. There are actually 2 loaders defined, one for component level SASS files and one for global SASS files.

          test: /\.scss$/,
          exclude: [/\.global\.scss$/],
          loaders: ['raw-loader', 'sass-loader']
        },
        {
          test: /\.global\.scss$/,
          loaders: ['style-loader', 'css-loader', 'sass-loader']
        }

Thanks to Shlomi Assaf's helpful blog post for this.

app.component.ts

The global SASS is loaded using require in the root level component. require('./app.component.global.scss');

home.component.ts

The component loads it own stylesheet in a similar manner. styles: [ require('./home.component.scss')]

The partials are then included inside the component SASS file. Unfortunately these need to be absolute paths. At least until I figure out how to use relative paths

@import './../../sass/_variables.scss';
@import './../../sass/_flex.scss';
All Posts