如何确保 webpack-dev-server 中的热 CSS 在 JS 之前加载? [英] How to ensure that hot CSS loads before JS in webpack-dev-server?

查看:16
本文介绍了如何确保 webpack-dev-server 中的热 CSS 在 JS 之前加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 webpack-dev-server 来热加载我的所有资产,包括 CSS.但目前,我的 CSS 在 JavaScript 之后加载,这导致我的应用程序在某些依赖现有布局的地方出现问题.

I'm using webpack-dev-server to hot load all of my assets including CSS. Currently though, my CSS loads after the JavaScript which causes my application issues in some places that depend on layout existing.

如何确保在 JavaScript 执行之前加载 CSS?

How can I ensure that the CSS loads before the JavaScript executes?

我认为必须有一种方法可以从 module 中做到这一点,也许是一个我可以挂钩的回调?或者也许通过配置样式加载器具有优先权?

I'm thinking there must be a way to do this from module, perhaps a a callback I could hook in to? Or maybe by configuring the style-loader to have priority?

这是我的 index.js:

This is my index.js:

import './styles/main.scss';
import './scripts/main.js';

if (module.hot) {
  module.hot.accept();
}

这是我的样式加载器:

{
        test: /\.(scss)$/,
        loader: 'style!css?&sourceMap!postcss!resolve-url!sass?sourceMap'
},

在这个 style-loader Github Issue 上也有人问过类似的问题:https://github.com/webpack/style-loader/issues/121

A similar question has been asked at this style-loader Github Issue: https://github.com/webpack/style-loader/issues/121

推荐答案

我遇到了完全相同的问题,在生产中 css 被提取出来所以它总是有效,但是在开发中因为 style-loader有时在主包之后执行"我遇到了问题,主包会计算由 css 设置的 DOM 中某些节点的大小......因此它可能导致错误的大小,因为主 css 仍未加载...我通过选项 singleton:true 解决了这个问题.

I was having the exacly same issue, in production the css are extracted so it always work, however in development because of the style-loader "sometimes executing after the main bundle" i had issues where the main bundle would calculate the size of some nodes in the DOM which was set by the css... so it could result to wrong sizes as the main css still havent loaded... i fixed this issue by having the option singleton:true.

示例:

{
    test: /\.s?css$/,
    loader: ExtractTextPlugin.extract({
            fallback: [
                {
                    loader: 'style-loader',
                    options: { singleton: true }
                }
            ],
            use: [
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 1,
                        minimize: !isProduction,
                        sourceMap: !isProduction
                    }
                },
                { loader: 'postcss-loader', options: { sourceMap: !isProduction, ...postcss } },
                { loader: 'resolve-url-loader', options: { sourceMap: !isProduction } },
                { loader: 'sass-loader', options: { sourceMap: true } }
            ]
        }
    )
}

这篇关于如何确保 webpack-dev-server 中的热 CSS 在 JS 之前加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆