Francesco Meli
Francesco Meli

Reputation: 2700

Webpack 4: SCSS to CSS into separate file

I would like to use Webpack 4 to transpile on one side my ES6 Javascript separately from my Sass:

Currently my webpack configuration seems to correctly transpile the javascript into a bundle.js but I cannot get my SCSS to transpile to CSS correctly.

I would definitely try to debug somehow but since I'm very ignorant on Webpack internals I'm not sure how to do it.

Following my webpack.config.js:

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

module.exports = {

  mode: 'development',

  entry: {
    bundle: './src/js/index.js',
  },

  output: {
    filename: '[name].js',
    path: path.resolve('static/js')
  },

  module: {
    rules: [{
      test: /\.scss$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          { loader: "css-loader" },     
          { 
            loader: "sass-loader",
            options: {
              includePaths: [
                path.resolve("./src/css")
              ]
            }
          },
        ]
      }),
    }]
  },

  plugins: [
    new ExtractTextPlugin({
      filename: path.resolve('static/css/style.css')
    })
  ],
}

Upvotes: 15

Views: 12711

Answers (2)

Ritwik
Ritwik

Reputation: 1725

Try mini-css-extract-plugin for webpack v4.

I created a separate webpack config file that looks like ...

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: './server/styles/styles.scss',
  output: {
    path: path.resolve(__dirname, 'public')
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "styles.css"
    })
  ],
  module: {
    rules: [
      {
        test: /\.s?css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  }
}

Not sure why, but it's also generating a javascript file with the required css bundle.

Upvotes: 17

pyran1208
pyran1208

Reputation: 115

extract-text-webpack-plugin does not play well with webpack 4.

According to Michael Ciniawsky:

extract-text-webpack-plugin reached a point where maintaining it become too much of a burden and it’s not the first time upgrading a major webpack version was complicated and cumbersome due to issues with it

mini-css-extract-plugin is here to overcome those issues.

see here for more information about this topic

Upvotes: 7

Related Questions