Webpack 4. Compile scss to separate css file

fortyfiveknots picture fortyfiveknots · May 17, 2018 · Viewed 16.1k times · Source

Im trying to compile scss into a separate css file with no luck. As it is now the css gets into the bundle.js together with all js code. How can i separate my css into its own file?

This is how my config looks.

var path = require("path");

module.exports = {
entry: "./js/main.js",
output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
    publicPath: "/dist"
},
watch:true,
module: {
    rules: [
        {
            test: /\.js$/,
            use: {
                loader: "babel-loader",
                options: { presets: ["es2015"] }
            }
        },
        {
            test: /\.scss$/,
            use: [
                {
                    loader: "style-loader"
                },
                {
                    loader: "css-loader"
                },
                {
                    loader: "sass-loader"
                }
            ]
        }
    ]
}

};

Answer

Fusion picture Fusion · Feb 2, 2020

Other answers gave me just headache as they were not working. I did a lot of googling and I realized you can compile scss into separate css file without using any additional plugins

webpack.config.js

const path = require('path');

module.exports = {
    entry: [
        __dirname + '/src/js/app.js',
        __dirname + '/src/scss/app.scss'
    ],
    output: {
        path: path.resolve(__dirname, 'dist'), 
        filename: 'js/app.min.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: [],
            }, {
                test: /\.scss$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'file-loader',
                        options: { outputPath: 'css/', name: '[name].min.css'}
                    },
                    'sass-loader'
                ]
            }
        ]
    }
};

package.json

{
  "name": "...",
  "version": "1.0.0",
  "description": "...",
  "private": true,
  "dependencies": {},
  "devDependencies": {
    "file-loader": "^5.0.2",
    "node-sass": "^4.13.1",
    "sass-loader": "^8.0.2",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  },
  "scripts": {
    "build": "webpack --config webpack.config.js --mode='production'"
  },
  "keywords": [],
  "author": "...",
  "license": "ISC"
}

Dependencies:

npm install --save-dev webpack webpack-cli file-loader node-sass sass-loader

How to run JS and SCSS compilation

npm run build