is there any way to dynamically load css file with webpack

9.5k views Asked by At

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

It is so weird since I dynamically load my js files while I load my css files only in one time.

In my project, I make my css files in seperate entries and use extractTextPlugin to compile them as a extra css files. And load them in link tag.

2

There are 2 answers

4
Ambroos On

You can, but they will not be loaded as CSS files (with ExtractTextPlugin), but from JS, injected with style-loader (which is perfectly alright).

There are only a few things to do. Make sure you set up your CSS/SASS/LESS/...-loaders correctly. If ExtractTextPlugin already works you're good on that point. Then also make sure you have fallbackLoader set to style-loader (and allChunks set to the default: false) in your ExtractTextPlugin.extract({}) loader.

At that point, just use require.ensure or System.import to require/import your CSS files, exactly as you would do with code. Thanks to the magic of webpack, things will just magically work!

0
Illuminati On

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

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