Reputation: 41
This is my second day working with Webpack bundler.
I am using mini-css-extract-plugin
loader.
Everything works as expected but when I import the css files dynamically I noticed some strange behaviour.
The problem is extra js chunk.
src/index.ts
:
import { data } from "./constants";
(async () => {
if (data.enableWidget) {
await import("./widget.css");
//...
} else {
//...
}
})();
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
//...
plugins: [
new MiniCssExtractPlugin()
//...
],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
//...
]
}
};
After bundling it generates corresponding files for app.bundle.js, widget.css but it also generates extra js chunk which is of very light size for each dynamic css import
And here is how it behaves: It loads bundle js, if condition is true it loads the js chunk then css.
But what's the point of loading that js chunk why it doesn't load css directly?
I don't want to make extra requests to load a css file as it make 1 extra request which delay css loading time.
Note that I am not sure if it is default behaviour or some other reason.
Upvotes: 0
Views: 176
Reputation: 3730
Webpack and mini-css-extract-plugin working fine.
When we import a file like this:
import "./my-custom.css";
It will load the css eagerly, means it will part of your js file. But in case of mini-css-extract. It extracts css to a file and adds a link tag to load the css file. However, when we use import syntax like this:
import("./my-custom.css")
It will load lazily via js thing. Reason behind this is lazy loading is the concept of js not css.
Upvotes: 0