Using SASS

Now, lets also add a .scss file and try to bundle it with webpack using sass-loader.

  1. Under the ./src/styles folder, add a couple of .scss files as below:


2. also add the file - ./src/styles/appStyles.scss

Above, we imported the ‘themeColors.scss’ in appStyles.scss (line# 1) and then defined styles for body tag using those theme-color variables.

3. Import the root scss file 'appStyles.scss' in app.js in order to have it considered as dependency by webpack:

4. Now, that we are using sass in our application, we will needsass-loader that would help webpack to compile sass to css.
So, lets install sass-loader.
sass-loader is dependent on another loader – node-sass, so we’ll have to install both.

$ npm install sass-loader node-sass --save-dev

5. Update the webpack.config.js to chain sass-loader , then css-loader and then chain their output to style-loader (Loader-chaining)


Above, we updated the rule a little bit to handle our sass and css files.
The test is now test: /\.(s*)css$/ : which means any file having name matching with the regular expression /\.(s*)css$/i.e. any .scss or .css file, should be compiled with the chain of loaders specified in the use array i.e. ['style-loader', 'css-loader', 'sass-loader']. As mentioned earlier, the loaders are chained in the reverse order.

Thus, this rule chain the output of sass-loader to css-loader. css-loader will take this css output of sass-loader and will also process any other .css files we have in our application and pass on the .css to style-loader, which will then do the job of putting the css codes inside <style> tags in our index.html

6. Run npm start again for webpack to run with the updated config options.

$ npm start

7. Refresh our application on the browser (localhost:9000), we should now see the styles from both the css and .scss files getting applied to the application, Yay!

In the next lesson, we will see how to use extract-text-plugin to extract the css that we have above within <style>..</style> in a separate .css file.

[Prev: Webpack Loaders, CSS and Styles] [ Next: extract-text-plugin ]