为什么 style-loader 被用作 Webpack 的 ExtractSass 插件的后备? [英] Why is style-loader used as a fallback with Webpack's ExtractSass plugin?

查看:23
本文介绍了为什么 style-loader 被用作 Webpack 的 ExtractSass 插件的后备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中(在这里),style-loader 被用作开发模式的后备.为什么?

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
    ]
};

推荐答案

从 JavaScript 中提取 CSS 主要用于在将 CSS 作为 <style> 标签,这会导致 无样式内容 (FOUC) 的闪现.当然,它也用于简单地将 CSS 与 JavaScript 分开,因为这通常是首选并且允许单独缓存.

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.

在开发中这并不重要,因为 FOUC 基本上是一个性能问题,就像您的 JavaScript 的加载时间一样,希望您在开发中也不会变得丑陋.这既不是您的主要关注点,也不是开发模式中的代表.除了作为一个额外的编译步骤之外,提取 CSS 还带来了一些缺点.例如,你失去了热重载,因为新编译的包没有随着 CSS 的内容被提取而改变.优点主要是您关心的生产方面,而缺点则对开发产生负面影响.另请参阅用法 - 优点和注意事项.

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.

要清楚,回退是在应用配置的加载器之后使用的,这只是一个额外的步骤,能够将 CSS 注入