-
Notifications
You must be signed in to change notification settings - Fork 29.5k
Description
Bug report
Describe the bug
Importing a stylesheet from a package is not possible in a page, because next throws with this error:
Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.tsx.
Read more: https://err.sh/next.js/css-global
While I understand where this stems from, it makes code-splitting impossible. If I import a component from a component library, I need to import the CSS as well. There might be libraries that don't correctly scope their selectors, but that shouldn't stop me from overwriting this warning. CSS that is imported from a library isn't inherently "global".
To Reproduce
import "my-library/index.css"
yarn dev
- I get the error from above
Expected behavior
The file should be imported.
I see these possible solutions:
- Global flag in
next.config.js
- Comment annotation on import
- Warn instead of completely blocking it
- Check if the CSS only contains scoped selectors
Additional context
There have been previous discussions about this.
From the blog
Since stylesheets are global by nature, they must be imported in the Custom component. This is necessary to avoid class name and ordering conflicts for global styles.
I disagree with this statement, the reasoning being that an external library can use CSS modules and package them as a CSS file to import. Which is perfectly valid and common practice and does not have side effects.
#10059
This issue got closed because the global import in _app
is the correct choice there.
This comment describes the exact problem, but there hasn't been any response, as the issue is closed. The comment got a lot of positive reactions though, so I suppose I'm not the only one with this problem.
#10975
Seems to be unrelated.
#9830
Might be related, but I'm not sure.
My use case
I write long articles with a lot of custom artwork and interactive illustrations. Articles use private npm packages with react components that render SVG with quite a bit of CSS. These packages use CSS modules and export an index.js
and index.css
. Adding all the CSS files to _app
causes all the CSS to be loaded, even if people are on the home page, the contact form, or any other article, even though it's 100% unused. It also goes against having the file system take care of your pages because almost every page corresponds to a CSS import in _app
.