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.

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.

These are the relevant parts from my webpack.config.json:

module.exports = (env = {}) => {
	return {
		entry: ['./assets/js/src/functions.js', './assets/css/scss/fanoe.scss'],
		output: {
			filename: 'assets/js/bundle.js',
		},
		module: {
			rules: [
				{
					test: /\.scss$/,
					use: [
						{
							loader: 'file-loader',
							options: {
								name: '[name].css',
								outputPath: 'assets/css/'
							}
						},
						{
							loader: 'extract-loader'
						},
						{
							loader: 'css-loader'
						},
						{
							loader: 'postcss-loader'
						},
						{
							loader: 'sass-loader'
						}
					]
				}
			]
		}
	}
};

With that, Webpack compiles the ./assets/css/scss/fanoe.scss to the fanoe.css inside the assets/css directory. 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):

"devDependencies": {
  "autoprefixer": "^7.1.2",
  "babel-core": "^6.26.0",
  "babel-loader": "^7.1.2",
  "babel-preset-env": "^1.6.0",
  "css-flip": "^0.5.0",
  "css-loader": "^0.28.7",
  "csso-cli": "^1.0.0",
  "extract-loader": "^1.0.1",
  "extract-text-webpack-plugin": "^3.0.0",
  "file-loader": "^0.11.2",
  "node-sass": "^4.5.3",
  "postcss-cli": "^4.1.0",
  "postcss-loader": "^2.0.6",
  "sass-loader": "^6.0.6",
  "webpack": "^3.5.6"
},

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

Related posts

Leave a Comment

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