SASS is a preprocessor that works with .scss (Sassy CSS) files and produces standard CSS files that browsers can work with. The preprocessing step is the key to using features that aren't (at least yet) available in CSS, such as variables, nested structures, inheritance, mixins, and many others. You can install and use SASS as a separate tool, but that isn't really too appealing; we'll aim to instead include it in the project, so all needed preprocessing will be done automatically. Let's see how to do that.
First, we need to install a tool. The developers of create-react-app didn't want to include a fixed CSS preprocessor, so you can really add whichever you want. There are several SASS tools, but the following one is recommended:
npm install node-sass-chokidar --save-dev
Second, we'll also have to add an extra line to the .flowconfig file, so .scss files will be properly recognized. The changed section would become as follows:
[options]
include_warnings=true
module.file_ext=.scss
.
.
.
Finally, we'll have to modify some scripts. SASS preprocessing will run in parallel to npm start, and for that we need a package that lets you run several commands in parallel:
npm install npm-run-all --save-dev
Now the changed scripts will be the following:
"build-scss": "node-sass-chokidar src/ -o src/",
"watch-scss": "npm run build-scss && node-sass-chokidar src/ -o src/ --watch --recursive",
"start-js": "react-app-rewired start",
"build-js": "react-app-rewired build",
"storybook-js": "start-storybook -p 9001 -c .storybook",
"start": "npm-run-all -p watch-scss start-js",
"build": "npm-run-all build-scss build-js",
"storybook": "npm-run-all -p watch-scss storybook-js",
.
.
.
Let's see what our new and updated processes do:
- build-scss converts .scss files in src/ to .css files; we'll be using the latter ones
- watch-scss does an initial conversion of SASS files, and then runs the conversion in watch mode, running whenever there are new or changed files to process
- start-js, build-js, and storybook-js are our old start, build, and storybook processes, which we won't be using directly
- start now runs both watch-scss and start-js, in parallel (because of the -p option)
- build now runs build-scss followed by build-js, so all SCSS will have been converted before building the application
- storybook runs both watch-scss and storybook-js, also in parallel
You are set! From now on, .scss files will be properly processed, and converted to .css files; let's see how we can make this work for us now.