Search code examples
csswebpacksassstylesheet

Sass Loader for webpack: How to get CSS file instead of inline styles?


I'm using webpack for my JS and SASS and it works. But now I want the CSS as a standalone stylesheet file and not as inline styles. What do I have to change in my webpack settings to achieve this?

Here is my current summarized webpack config:

{
    entry: {
        'plugin': './src/js/index.js',
    },
    output: {
        filename: '[name].js',
    },
    module: {
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader",
            }]
        }]
    }
}

I've used the official docs of SASS Loader and I know from the Style Loader docs that I've to use the File Loader too. But I'm at the end of my knowledge and need your help. All my trail-and-error configs failed.

Thanks for your help!


Solution

  • You have to install mini-css-extract-plugin to be able to remove css from js files and put them into separated .css files.

    const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // <--- INSTALL THIS
    module.exports = {
        entry: {
            'plugin': './src/js/index.js',
        },
        output: {
            filename: '[name].js',
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader, "css-loader"]
                },
                {
                    test: /\.scss$/,
                    use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
                }
            ]
        },
        plugin: [
            new MiniCssExtractPlugin()
        ]
    }