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.
Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.
To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.
Loaders are the node-based utilities built for webpack to help webpack to compile and/or transform a given type of resource that can be bundled as a javascript module. css-loader is the npm module that would help webpack to collect CSS from all the css files referenced in your application and put it into a string.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With