Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to dynamically load css file with webpack

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.

like image 275
Zero Avatar asked Dec 21 '16 09:12

Zero


People also ask

How do I dynamically load CSS files?

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.

How do I load a CSS file into webpack?

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.

Does webpack compile CSS?

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.


1 Answers

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!

like image 200
Ambroos Avatar answered Nov 27 '22 14:11

Ambroos