Search code examples
cssreactjssasswebpackwebpack-style-loader

How to precompile scss to a single css file in webpack?


Using React with webpack. Ran through some articles, but most of them suggest calling individual scss file for each component. But I would like to precompile all css into single file for entire application like we do using grunt/gulp.

enter image description here


Solution

  • You can use the webpack-text-extract-pluggin that is in charge of compiling all css files and bundling them in an index.css file.

    Also note that you'll need to install sass-loader too in order to compile the scss.

    In the webpack config:

    var ExtractTextPlugin = require('extract-text-webpack-plugin');
    config = {
        ..., 
        plugins: [
            ...,
            new ExtractTextPlugin('index.css')
        ],
        module: {
            loaders: [
                ...
                {
                    test: /\.css$/,
                    loader: ExtractTextPlugin.extract('style','css')
                },
                {
                    test: /\.scss$/,
                    loader: ExtractTextPlugin.extract('style', 'css!sass')
                }
            ]
        }
    }
    

    In index.html:

    <link rel="stylesheet" type="text/css" href="/index.css">
    

    In any Javascript file that gets through webpack:

    require("./styles/my-custom-file.scss");