next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Inconsistent CSS resolution order

Open GabenGar opened this issue 1 year ago • 48 comments

Link to the code that reproduces this issue

https://github.com/GabenGar/repros/blob/main/nextjs/css-out-of-order/README.md

To Reproduce

Reproduction steps are in the README.md

Current vs. Expected behavior

Current: Different CSS resolution order between development and production. Before I had weird client vs. render CSS issues, but it looks like they are fixed in 14.2, although they weren't super reproducible before either. Expected: Work basically like pages router.

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10
  Available memory (MB): 7990
  Available CPU cores: 4
Binaries:
  Node: 20.9.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.2 // Latest available version is detected (14.2.2).
  eslint-config-next: 14.2.2
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Not sure

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local), next start (local), Vercel (Deployed)

Additional context

No response

GabenGar avatar Apr 23 '24 14:04 GabenGar

It seems 14.2.2 fixed this for development but not for prod.

GabenGar avatar Apr 23 '24 15:04 GabenGar

@GabenGar Thanks for sharing a :repro:—we will be taking a look at this!

samcx avatar Apr 24 '24 21:04 samcx

We are seeing the same issue on 14.2.2 where on production builds the CSS styles get included in an unexpected order.

The specific example we are seeing is that CSS styles imported into layout.js are overriding CSS styles set in a component level stylesheet even though they have the same CSS specificity and the component CSS should override the layout's CSS. This bug appears to be due to the order that the CSS is included in the final static .css files that are included in the production build.

benjitastic avatar Apr 27 '24 01:04 benjitastic

@benjitastic What kind of CSS styling are you using in this case (e.g., css modules)?

samcx avatar May 01 '24 22:05 samcx

@benjitastic What kind of CSS styling are you using in this case (e.g., css modules)?

No, not modules. Just like this inside the component:

import './styles.css'


Some more details:

In this case layout.js had this at the top: import '@/styles/customTheme.scss'

And customTheme.scss had this inside it: @import 'bootstrap/scss/bootstrap';

That bootstrap file has a css style declared for .btn like this: .btn { padding: .375rem .75rem }

Then in the component we have an element <button className="btn filter-pill"> and that component includes a styles.css. Inside that styles.css there's this declaration: .filter-pill { padding: 8px 33px 8px 14px }

The expectation is that .filter-pill padding can override .btn padding. But .btn was overriding .filter-pill styles. This was because of the 5 /_next/static/css/*.css files appearing in the DOM the 1st one contained .filter-pill and the 2nd one contained .btn. This is backwards from expected order. Regardless of it they are in the same static CSS file or not the .btn declaration should come before the .filter-pill declaration.

Hard to post a repro since I think you need a project that has enough CSS to result in multiple static CSS files being generated.

We reverted back to 14.1.4 and the CSS went back to the correct order.

benjitastic avatar May 02 '24 04:05 benjitastic

I am seeing this issue as well, particularly for global styles as well as styles using css modules. As mentioned in this issue, it only happens in production builds.

paulyi avatar May 16 '24 00:05 paulyi

Setting experimental: { cssChunking: 'strict' } in next.config.js resolves this issue for us. Not ideal, but better than broken CSS ordering in production!

dstaley avatar May 22 '24 01:05 dstaley

Setting experimental: { cssChunking: 'strict' } in next.config.js resolves this issue for us. Not ideal, but better than broken CSS ordering in production!

Interesting -- I can't find any docs anywhere on the cssChunking parameter.

Does anybody know exactly what "strict" css chunking does?

benjitastic avatar May 22 '24 17:05 benjitastic

Setting experimental: { cssChunking: 'strict' } in next.config.js resolves this issue for us. Not ideal, but better than broken CSS ordering in production!

It does not seem to resolve the issue for us :(

Netail avatar May 23 '24 20:05 Netail

Are there any updates on this issue from the nextjs team?

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

paulyi avatar May 23 '24 21:05 paulyi

@Netail Thanks for sharing.

Are there any updates on this issue from the nextjs team?

I can confirm there are several broken cases with the ordering of CSS, after looking at several :repro:s. We've been busy with the 15 release—since that's out of the way, we will be prioritizing this!

Does anybody know exactly what "strict" css chunking does?

Getting some answers internally to further clarify this—will respond back soon!

samcx avatar May 24 '24 23:05 samcx

That would be great. We use a design system package and a navigation package which uses the design system package (with some overrides) and the app using the design system, but the overwrites are currently not working on productions. Thus making NextJS kind of unusable currently for us. So the sooner the better 😅

Do you by any chance have a ETA when development on this will happen?

Netail avatar May 24 '24 23:05 Netail

Can confirm this issue also comes up in a project using Next.js 14.2., Mantine v7.10 components, and css modules. Works fine in development mode, loads incorrectly in production.

mrabuse avatar May 28 '24 19:05 mrabuse

I had a similar issue, where global styles were bundled after component styles. Running dev I never had an issue, only on production. I'm using Next 14.2.2 with App router and SSG.

My workaround is only for getting global scss that's imported in layout.js to load ahead of client component scss modules. But perhaps this will be helpful for someone else / debugging the overall issue.

In my root layout.js I was importing /global.scss

There is an @import css rule in there that should be loaded first since that is the first css imported on the page and before any components. However, in dev tools I had the following Issue: An @import rule was ignored because it wasn't defined at the top.

Indeed there was css rules added above the global.scss.

After analyzing it seems that the css above my @import was all related to client components. This led me to believe that next must prioritize client component styles when bundling css during production builds.

My workaround fix is to make a new client component that imports the styles

"use client";

import "@/scss/global.scss";
const GlobalStyles = () => {
    return <></>;
};

export default GlobalStyles;

and then import that component in my root layout.js

import GlobalStyles from "./GlobalStyles";
export default function RootLayout({ children }) {
    return (
        <html lang="en">
            <GlobalStyles />
            <body>
                {children}
            </body>
        </html>
    );
}

This resolved the issues I was getting in dev tools, and also some issues with specificity (component styles were no longer overriding global styles before the workaround).

michaelkostal avatar May 29 '24 19:05 michaelkostal

Do you by any chance have a ETA when development on this will happen?

@Netail No ETA to share yet, but this issue is definitely high on our plate!

samcx avatar May 29 '24 23:05 samcx

I noticed that if I replace getModuleReferencesInOrder with moduleGraph.getOutgoingConnections(module) my classes are all back in the order I expect (with some minor duplication of different hashes) *that part was a different experiment. This is a major issue in my org preventing further adoption of server components and merging of prs so it hopefully is just a little tweaking to the module reference logic.

I believe this regression was introduced here as part of the 14.2 release.

Edit: It appears that removing the sorting also results in the correct order

piratetaco avatar Jul 02 '24 14:07 piratetaco

@piratetaco Is it possible to :repro: so we can take a closer look?

@michaelkostal Can you try testing a later Next.js version? I believe this :pr: fix (https://github.com/vercel/next.js/pull/63157) was not backported to 14.2.2. You can also try the latest canary (greater than v15.0.0-canary.56), which has an additional fix → https://github.com/vercel/next.js/pull/67373.

samcx avatar Jul 08 '24 08:07 samcx

@samcx I face this issue on 14.2.3 as well. Can we backport the additional bug fix to v14 as well for those who cannot switch to a canary version or upgrade a major version at this time?

paulyi avatar Jul 08 '24 22:07 paulyi

@paulyi The latest changes should now be in 14.2.5 (includes both fixes mentioned above).

samcx avatar Jul 10 '24 22:07 samcx

@samcx just tried out the 14.2.5 release -- while this release is an improvement, I'm still seeing some incorrect loading of css in the production environment.

mrabuse avatar Jul 10 '24 22:07 mrabuse

@mrabuse :frog-eyes:

Can you describe exactly how it's loading incorrectly, and is it possible to provide a minimal, public :repro: so we can take a look?

samcx avatar Jul 11 '24 10:07 samcx

It'll take me a bit to build a public repro for you, but I'll see if I have some time this weekend. The project I'm working on uses Mantine UI for our component library, which has a base styles css file that must be loaded first. Those are imported at the top of our layout.tsx file from the Mantine package (import '@mantine/core/styles.css';). We then use per-file css modules to further style components. In production on 14.2.5, I'm seeing that the imported base styles file gets loaded after all of our css modules, switching the override order.

mrabuse avatar Jul 11 '24 16:07 mrabuse

@michaelkostal Can you try testing a later Next.js version? I believe this :pr: fix (#63157) was not backported to 14.2.2. You can also try the latest canary (greater than v15.0.0-canary.56), which has an additional fix → #67373.

@samcx upgrading to 14.2.5 did resolve my issue. It now appears my global styles are loaded first in order as expected. Thanks!

michaelkostal avatar Jul 11 '24 17:07 michaelkostal

Those are imported at the top of our layout.tsx file from the Mantine package (import '@mantine/core/styles.css';). We then use per-file css modules to further style components. In production on 14.2.5, I'm seeing that the imported base styles file gets loaded after all of our css modules, switching the override order.

@mrabuse :frog-eyes:. Where exactly do you see the order being incorrect (e.g., in a Page that's a Client Component or a Server Component?) Seems like you're doing it all correctly, so a :repro: will be great.

@michaelkostal That's great to hear!

samcx avatar Jul 12 '24 12:07 samcx

sadly I'm unable to get a public repro going. The issue only seems to appear after the components are mixing and matching through the entire component library we're maintaining - but the issue we are seeing is still happening as of 14.2.5.

For now we are going to import higher stylesheets in the component.js in our library as a cumbersome workaround.

import { FirstButton } from '../FirstButton'
// styles that are going out of order
import '../FirstButton.styles.module.scss'
// component styles that should __always__ be added after FirstButton styles based on import order but are not
import styles from './styles.module.scss'

...

piratetaco avatar Jul 12 '24 17:07 piratetaco

The issue still persist as of 14.2.5 version, I'm using Sass with CSS Modules and I get inconsistent css import order between running the dev server locally and the production build, my app is quite big and I cannot get you a public repo up. Also this doesn't happen on small projects where only 1 chunk of css is build, in my case I have 5/6 chunks of css being build and I can't really reproduce something of that magnitude.

Screenshot 2024-07-17 at 18 03 01 Screenshot 2024-07-17 at 18 03 38

In this case its a composed component from an atom where I want to overwrite the gap, locally all works as expected but when building the project the css imported chunks order is being mixed.

My only solution at the moment is the one suggested by @piratetaco but I have a huge project, please fix this!

consdu avatar Jul 18 '24 08:07 consdu

The issue still persist as of 14.2.5 version, I'm using Sass with CSS Modules and I get inconsistent css import order between running the dev server locally and the production build, my app is quite big and I cannot get you a public repo up. Also this doesn't happen on small projects where only 1 chunk of css is build, in my case I have 5/6 chunks of css being build and I can't really reproduce something of that magnitude.

Screenshot 2024-07-17 at 18 03 01 Screenshot 2024-07-17 at 18 03 38 In this case its a composed component from an atom where I want to overwrite the gap, locally all works as expected but when building the project the css imported chunks order is being mixed.

My only solution at the moment is the one suggested by @piratetaco but I have a huge project, please fix this!

+1 on this only surfacing once your app generates multiple chunk files. Your explanation of the issue matches exactly the symptoms we reported back in May. I'm still sitting at v14.1.4 and we are waiting to upgrade until this has been resolved, we are not yet considering implementing any work-arounds described in this issue thread as they are cumbersome to implement and maintain.

benjitastic avatar Jul 18 '24 17:07 benjitastic

@consdu Can you also try using this experimental option (if you haven't yet)?

experimental: {
  cssChunking: "strict" // default is "loose"
}

x-ref: https://github.com/vercel/next.js/pull/67691/files

samcx avatar Jul 19 '24 10:07 samcx

@consdu Can you also try using this experimental option (if you haven't yet)?

experimental: {
  cssChunking: "strict" // default is "loose"
}

x-ref: https://github.com/vercel/next.js/pull/67691/files

@samcx

I did that yes. I'm currently using version 14.1.1, which I believe didn't include the flag you mentioned. I upgraded to version 14.2.5 and set the flag to "strict", but unfortunately, the issue persists. I even tried downgrading to version 13, but the problem remained, suggesting that it's not related to changes introduced in version 14 and above.

I'm using the pages router for my project. I'm happy to provide more screenshots and details about my configuration if needed.

consdu avatar Jul 19 '24 11:07 consdu

@consdu I see. Just to clarify, the fixes that have been pushed recently all relate to App Router, not Pages Router.

Are you using a postcss.config.js file by any chance? If yes, can you share your config?

samcx avatar Jul 19 '24 12:07 samcx