How to ensure that hot CSS downloads to JS in webpack-dev server?

I use webpack-dev server to load all my assets, including CSS. My CSS is currently loading after JavaScript, which causes my application problems in some places that depend on the existing layout.

How can I ensure CSS is loaded before JavaScript is executed?

I think there should be a way to do this from module , perhaps a callback to which I could connect? Or maybe when setting up the bootloader style, priority?

This is my index.js:

 import './styles/main.scss'; import './scripts/main.js'; if (module.hot) { module.hot.accept(); } 

and this is my styleloader:

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

In this downloader style, a similar question was asked by Github Issue: https://github.com/webpack/style-loader/issues/121

+5
source share
3 answers

There seems to be no event, callback, or in any way detect that the style has been loaded. After long hours of searching in vain, I had to do something really dirty:

 function checkCSS() { const repeat = requestAnimationFrame(checkCSS); // CSS loaded? if(getComputedStyle(document.body).boxSizing === 'border-box') { routes.loadEvents() // Init JS cancelAnimationFrame(repeat) // Cancel next frame } } if (process.env.NODE_ENV !== 'production') { checkCSS() } else { $(document).ready(() => { routes.loadEvents() }) } 

Since I have * { box-sizing: border-box; } * { box-sizing: border-box; } in my styles, and I'm sure that the native CSS styles will never look like this, I can be 99% sure that my own CSS is loaded.

I died a bit by writing this. Hope we find a better way!

0
source

I had one and the same problem: in css production they are extracted, therefore it always works, however in development because of the style-loader "sometimes executed after the main package" I had problems when the main package calculated the size of some nodes in the DOM, which was installed by css ... so this can lead to incorrect sizes, since the main css is still loaded ... I fixed this problem by selecting the singleton:true option.

Example:

 { 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 } } ] } ) } 
0
source

You can use extract-text-webpack-plugin .

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

Then in your HTML, link the CSS file to <head> with <link rel="stylesheet" ... so that it loads before JS.

HMR is not compatible with ExtractTextPlugin, but at least it does CSS loading before JS.

-2
source

All Articles