Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is style-loader used as a fallback with Webpack's ExtractSass plugin?

In the following example (found here), style-loader is being used as a fallback in development mode. Why?

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

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: process.env.NODE_ENV === "development"
});

module.exports = {
    ...
    module: {
        rules: [{
            test: /\.scss$/,
            use: extractSass.extract({
                use: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }],
                // use style-loader in development
                fallback: "style-loader"
            })
        }]
    },
    plugins: [
        extractSass
    ]
};
like image 745
charliesneath Avatar asked Apr 14 '17 00:04

charliesneath


1 Answers

Extracting CSS from JavaScript is primarily used to not having to rely on your JavaScript (the bundle) being fully loaded until it injects the CSS into the head as a <style> tag, which can cause Flash of unstyled content (FOUC). And of course it's also used to simply separate CSS from JavaScript because that's generally preferred and allows being cached separately.

In development this doesn't really matter since the FOUC is basically a performance issue, just like the load time of your JavaScript, which hopefully you don't uglify in development either. This is neither your main concern nor representative in development mode. Besides being an additional compilation step, extracting CSS also imposes some drawbacks. For instance you lose hot reloading, because the newly compiled bundle didn't change as the content of the CSS has been extracted. The advantages are mostly aspects you care about for production and the drawbacks negatively affect development. See also Usage - Advantages and Caveats.

To be clear, the fallback is used after the configured loaders have been applied, it's just an extra step to be able to inject the CSS into a <style> tag from your JavaScript, which is the only thing that style-loader does. The fallback is used instead of extracting it to a file.

like image 59
Michael Jungo Avatar answered Sep 23 '22 16:09

Michael Jungo