Using Node-Sass to Watch Sass Files
Compiling all that Sass into a single CSS file.
This is a short post to share the setup for SASS in our WIP Reactified Portal. The previous setup was non-existent, our resident CSS-expert would use a tool (which used Gulp) to compile every scss file into a single CSS sheet and then import it into our shared ‘layout’ partial view.
Use Case
So we have a set of scss files serving the remainder of our MVC cshtml pages, as well as a bunch of React components which, as of right now, mimic the way our MVC views used to work.
Because the CSS for EVERY page had to be compiled into one file, I couldn’t rely on the MiniCssExtract plugin.
Note: The plan is to migrate our styling to CSSModules from CreateReactApp, but for now, the single file works just fine.
The Solution
The webpack config quite simple. For now, it doesn’t need to worry about CSS imports into components, it singularly focuses on the JSX.
Node-Sass
Node-sass is a library that provides binding for Node.js to Sass.
It allows you to natively compile .scss files to css at incredible speed and automatically via a connect middleware.
Once installed with NPM (‘npm install node-sass’), add another script to your package.json file:
Which adds another script to NpmTaskRunner:
Whenever a change is detected in our style.scss file (after hitting ctrl+s), node-sass picks it up and compiles into wwwroot/css/style.css.
The example above will only work if you’re importing all of your SASS components into one component, then watching that file. Otherwise you can supply the parent folder as the first argument after -watch and it should compile separate CSS files for each component in that folder.
Realising Node-Sass could be utilised in this way saved a huge webpack config headache.
If you’re importing CSS modules in your components (which we haven’t adopted yet), then using node-sass or other loaders in your webpack configuration is definitely the way to go, but this works if your front-end development setup is similar to ours!