Compile SASS with Webpack into a CSS file

It is not trivial to compile an SCSS file with Webpack, which is not included in the JS file, into its own CSS file. This post shows you how to do that.

Update from September 6, 2018: I updated the post to show a solution with Webpack 4.

I needed this because I had to use Webpack for a project and did not want to use another tool for compiling the SASS. At the end of my search, the solution was to use the extract-loader.

This is my webpack.config.json:

const path = require('path');

module.exports = {
	mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
	entry: ['./blocks/index.js', './blocks/editor.scss', './blocks/frontend.scss'],
	output: {
		path: path.resolve(__dirname, 'assets'),
		filename: 'js/editor.blocks.js',
	module: {
		rules: [
				test: /\.scss$/,
				use: [
						loader: 'file-loader',
						options: {
							name: 'css/[name].blocks.css',
						loader: 'extract-loader'
						loader: 'css-loader?-url'
						loader: 'postcss-loader'
						loader: 'sass-loader'

With that, Webpack compiles the ./blocks/editor.scss to the editor.blocks.css inside the assets/css directory and the ./blocks/frontend.scss to the assets/css/frontend.blocks.css. The postcss-loader runs Autoprefixer. To get that working, I created a postcss.config.js with the following content:

module.exports = {
	plugins: {
		'autoprefixer': {}

These are the dev dependencies from my package.json (a few are not necessary for the Webpack task) and the NPM tasks to run Webpack:

"scripts": {
  "build:dev": "webpack",
  "build:production": "cross-env NODE_ENV=production webpack",
  "watch": "webpack --watch"
"devDependencies": {
  "@babel/core": "^7.0.0",
  "@wordpress/babel-preset-default": "^2.1.0",
  "@babel/runtime-corejs2": "^7.0.0",
  "autoprefixer": "^9.1.3",
  "babel-loader": "^8.0.0",
  "cross-env": "^5.2.0",
  "css-loader": "^1.0.0",
  "extract-loader": "^2.0.1",
  "file-loader": "^2.0.0",
  "node-sass": "^4.9.3",
  "postcss-cli": "^6.0.0",
  "postcss-loader": "^3.0.0",
  "sass-loader": "^7.1.0",
  "webpack": "^4.17.2",
  "webpack-cli": "^3.1.0"

Now, if I run the webpack command, I get my SASS compiled into CSS.

Related posts

11 comments on »Compile SASS with Webpack into a CSS file«

  1. Josh

    Hello Florian. Thanks for this tuto, but it is not woeking for me. I am using Webpack 4. I did all your changes, but when i execute 'npm webpack' i recieve an error:

    "ERROR in .[...filepath...]
    Module build failed (from ./node_modules/postcss-loader/lib/index.js):
    TypeError: Cannot read property 'type' of undefined"

    Do you know what can be wrong here? Thanks!

    1. Florian Brinkmann

      Hi Josh,

      I updated the post to show a working example with Webpack 4. Would you give it a try and test if that fixes the problem (the dependencies in the package.json also changed)?



Leave a Comment

Your email address will not be published. Required fields are marked *