Should you use WebPack for building SCSS?

20th Jun 2019

In a previous post, I outlined how you could use WebPack to have different build outputs for development and production.

If you read that post, it should be clear that bundling and uglifying your JavaScript with webpack is very straightforward. However, getting webpack to do other front end build operations, such as compile SCSS before uglifying and bundling the generated CSS, is not a simple task. In fact, it's something I feel I put too much time into.

Since that post, I've updated that project so that webpack does one thing - bundle JavaScript.

All of the other build operations (compile SCSS, etc) are now being done in the simplest way possible - Yarn / NPM scripts.

These were previously jobs we'd leave to a task runner, like gulp. These worked and were reliable, but they had their downsides:

  • More gulp specific packages would be needed to act as a glue between the task runner and the task (e.g. gulp-sass)
  • Debugging a massive set of piped streams was not easy, and often needed more packages installed to do so (see gulp-debug)
  • Managing the parallel nature of these tasks was often tricky, and sometimes required even more packages installed to help you orchestrate the order

You don't need a task runner

Instead of using gulp or webpack for our entire font end build, we're going to use yarn / NPM scripts. So, let's start with our SCSS. We can use node-sass package to compile our SCSS into CSS files:

yarn add node-scss --dev

Now we just need to add a command into the "scripts" section of our package.json file that will call the node-scss package:

...
"scripts": {
"build-scss": "node-sass --omit-source-map-url styles/appstyles.scss dist/css/appstyles.css"
}

It's basically a macro command. Calling "build-scss" is a shortcut for the longer command that we've entered into our package.json file. Here's how we call it:

yarn run build-scss

Now let's add another script to call webpack so that it can do what it's good at - bundling our JavaScript modules:

...
"scripts": {
"build-scss": "node-sass --omit-source-map-url styles/appstyles.scss dist/css/appstyles.css",
"build-js": "webpack --mode=development"
}

Which now means that we can run:

yarn run build-js

To build our JavaScript.

Bringing it all together

We've now got two different yarn script commands. I don't want to run two commands every time I need to run a front-end build, so wouldn't it be great if I could run these two commands with a single "build" command? Yes it would!

...
"scripts": {
"build-scss": "node-sass --omit-source-map-url styles/appstyles.scss dist/css/appstyles.css",
"build-js": "webpack --mode=development",
"build": "yarn run build-scss && yarn run build-js"
}

All we need to do now is run

yarn run build

And our CSS and JavaScript will be generated. You could add more steps and more yarn scripts as needed - for example, a step to uglify your generated CSS.