Compile and convert SCSS files into a single CSS file using Webpack

Nov 9, 2017 Webpack 中文版

Webpack is a powerful tool that allows developers to compile and bundle JS files easily. But we can achieve more than that. For example, we can transfer SCSS files into CSS files. This post is about how to simply compile and convert SCSS files into a single CSS file.



Prerequisite

In order to compile SCSS files through Webpack, we have to install css-loader, sass-loader and other packages. So, let’s install them:

npm install --save-dev css-loader sass-loader node-sass extract-text-webpack-plugin

After installation, we need to make changes to Webpack config.

Change Webpack config

Let’s add loaders and related setting into Webpack config:

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: [
    // Specify scss files
    path.join(__dirname, 'path', 'to', 'scss', 'style1.scss'),
    path.join(__dirname, 'path', 'to', 'scss', 'style2.scss')
  ],
  output: {
    ...
  },
  module: {
    // Add loader
    rules: [{
      test: /\.(scss)$/,
      loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
    }]
  },
  plugins: [
    // Specify output file name and path
    new ExtractTextPlugin({
      filename: 'path/to/css/style.css'
    })
  ]
};

There are various ways of configuring Webpack config. Above is a basic example.


You might also like:




If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.