Adding SASS/SCSS to your React + TypeScript project

The Executioner
3 min readJan 7, 2019

--

If you have worked with CSS before then you truly know the pain of working with a large project with thousands of lines of styling where you change one single style to a button and then half of your page is overflowed off the page.

Sass somewhat solves this problem by making it easier to organise your code and help keep it DRY. It also provides other benefits such as nesting and mixins which you can think of as handy functions for css.

When using react the benefits of using sass/scss are somewhat reduced because we tend to use nested components and component composition however sass still provides nice flexible organisation of our styling.

Adding sass/scss to your project

We first start off with an existing project or if you haven’t got a react + typescript project yet follow the first couple of steps from this post.

  1. We need to install SASS and its typing file if you are using typescript.
npm i -D node-sass
npm i -D @types/node-sass

2. Next we create our .scss files. This can either be in the same folder as your components or maybe you have a seperate styles folder which hosts all your styling.

Folder structure

3. In your component .js or .tsx file we need to import the .css file. Note that this file will not exist yet but don’t worry when we create our build script node sass will automatically create these css files for us.

4. Now we need to tell npm how to build/watch these files for us. Firstly we need to install this module.

npm i -D npm-run-all

This module will be used to run node scripts in parallel by using the -p option which will allow us to watch our css files and build our js/typescript application.

5. Lastly we create the following npm run scripts.

"scripts": {
"build:css": "node-sass src/ -o src/ ",
"watch:css": "npm run build:css && node-sass src/ -o src/ -w -r",
"start:js": "react-scripts-ts start",
"start": "npm-run-all -p watch:css start:js",
"build:js": "react-scripts-ts build",
"build": "npm-run-all build:*",
"test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject",
},

The -o option simply tells node-sass that we want to generate output css files and where we want them to be. In our case this is the src folder but if you decided to keep all your styles together in one folder then you may need to change your build and watch:css scripts accordingly.

Conclusion

If you are looking to go one step further with your styling then check out the auto-prefixer package which is used by Google, Twitter and Alibaba.

As always if this post helped you at all in any way then please show your support.

--

--