Is there a way to dynamically load a css file using webpack

Webpack has code splitting frames (use require.ensure or System.import) that force us to dynamically load our js files. But I want to know if there is a way to dynamically load a css file?

It is so strange that I dynamically upload js files when I load css files only at a time.

In my project, I make my css files in separate entries and use extractTextPlugin to compile them as additional css files. And load them into the link tag.

+6
source share
2 answers

You can, but they won’t load as CSS files (with ExtractTextPlugin), but from JS that introduces the loader style (this is completely normal).

There are only a few things. Make sure you have configured the CSS / SASS / LESS /...- loader correctly. If ExtractTextPlugin is already working, you are well versed in this issue. Then also make sure fallbackLoader set to style-loader (and allChunks set to the default value: false ) in your ExtractTextPlugin.extract({}) loader.

At this point, just use require.ensure or System.import to require / import your CSS files, just like with the code. Thanks to the magic of webpack, everything will just magically work!

+1
source

I have successfully used the following setting to dynamically load styles for different tenants.

https://github.com/shiranGinige/react-redux-starter-with-login/blob/master/README.md

-one
source

Source: https://habr.com/ru/post/1013380/


All Articles