Webpack Skips CSS Import
Avoid the problem of Webpack not importing CSS stylesheets.
Webpack bundles your app, but sometimes it leaves something out. Is there a warranty on this thing? Can I get my npm bucks back? What is going on here?
Simple enough: A
.js file imports a
But the styles are not showing up on the page, even though my css loaders are flawless.
Webpack is tree-shaking
Webpack's getting blamed, and it feels sad. It's just doing its job. These days, Webpack is tree shaking by default. It's gotten better. It's trying to keep unused things out of your app bundle. It's cleaning up your mess! All that dead code in your source tree. Instead of telling you to clean up your room, it just dutifully cleans up what it detects as unused.
A CSS import looks suspiciously unused. There's no binding to a local variable or usage of that var. Also importantly, the file that imports it might also look worthless if it does nothing but import CSS. But we need both those things to avoid getting thrown out while Webpack does the dirty work of tree shaking.
Whitelist CSS as sideEffects
Webpack will respect a
sideEffects array in your
package.json. Things in this array will not be tree-shaken, no matter what. Maybe it's that stack of papers that you don't want moved or that pile of clothing with your favorite shirt or that mystery pile in the corner that is starting to decompose.
Usually, files that don't create side effects (pure ones) can be removed cleanly if they're not referenced (used). But you have some files that you want included that aren't programmatically used (eg, this CSS stylesheet) but nevertheless need included at runtime.
So let's add the stylesheet and file with the CSS import to the list in
"sideEffects": [ "**/*.css", "src/my-importing-file.js" ]
Build again, run again, whatever it is, and Webpack will leave your CSS in tact, and the styles that weren't loading should be there.
If they're not, this was a great article, but you have a different problem. Probably time to start looking at those "flawless" loaders.