Search code examples
csswebpacksasspostcss-loader

Webpack scss loader, css loader and post css


I'm trying to set up webpack for an app that uses ES6 classes. I use Sass, but there is also a vendor css file that I import. The sass partials are imported to sytle.scss uing @import. It worked all fine until before I added postcss loader, but now I get an error message when I try to compile and it fails.

In webpack.config.js:

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css"
})

const config = {
    .
    .
    .

    module: {
        rules: [{
            test: /\.(scss|css)$/,
            use: extractSass.extract({
                use: [{
                    loader: "sass-loader", options: {
                        sourceMap: true
                    }},
                    {
                        loader: "postcss-loader",
                        options: {
                            sourceMap: true
                        }
                    },
                    { 
                        loader: "css-loader", options: {
                        sourceMap: true,
                        importLoaders: 3,
                        modules: true
                    }}
                ],
                fallback: "style-loader"
            })
        }
       ]
      },
     plugins: [
        extractSass
        ...
     ]
  }

postcss.config.js:

module.exports = {
    plugins: {
      'postcss-import': true,
      'autoprefixer': {browsers: ['> 5%', 'last 3 versions']},
    }
}

In app.js:

import '../../scss/style.scss'
import '../../scss/vendors/select2.css;

This is the error:

ERROR in ./node_modules/sass-loader/lib/loader.js?{"sourceMap":true}!./node_modules/postcss-loader/lib?{"sourceMap":true}!./node_modules/style-loader!./node_modules/css-loader?{"sourceMap":true,"importLoaders":3,"modules":true}!../scss/style.scss
Module build failed: Syntax Error 

(5:1) Unknown word

  3 | // load the styles
  4 | var content = require("!!../offline/node_modules/css-loader/index.js?{\"sourceMap\":true,\"importLoaders\":3,\"modules\":true}!./style.scss");
> 5 | if(typeof content === 'string') content = [[module.id, content, '']];
    | ^
  6 | // Prepare cssTransformation
  7 | var transform;

Solution

  • When chaining loaders, they are applied right to left. In your case, you are trying to use a css-loader first on a scss file.

    Try to reverse the order of your loaders

            use: [{
                { 
                    loader: "css-loader", options: {
                    sourceMap: true,
                    importLoaders: 3,
                    modules: true
                }},
                {
                    loader: "postcss-loader",
                    options: {
                        sourceMap: true
                    }
                },
                loader: "sass-loader", options: {
                    sourceMap: true
                }}
            ],