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

[NEXT-1308] Css is imported multiple times and out of order in /app dir

Open ssijak opened this issue 1 year ago • 96 comments

Verify canary release

  • [X] I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.5.0: Mon Apr 24 20:52:24 PDT 2023; root:xnu-8796.121.2~5/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.12.1
      npm: 8.19.2
      Yarn: 1.22.19
      pnpm: 7.18.1
    Relevant packages:
      next: 13.4.5-canary.9
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.1.3

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/ssijak/next-css-issue-not-working-simple

To Reproduce

Just start the app and check the styling on the buttons. Styles are imported multiple times wherever Button was used (page and layout) and order is also not deterministic, so it can be imported in different order on different app runs.

This is another/same simple repro difference is just that it uses turbo and transpiles the UI lib, I started with that but figured that the issue is happening without it too https://github.com/ssijak/next-css-issue-not-working

Describe the Bug

-Same styles are imported multiple times -Order of imports is not deterministic

Screenshot: https://share.cleanshot.com/nq35j7vh

Expected Behavior

Same styles should be imported once. Starting the app multiple times should not produce different results (ordering of CSS, impacting specificity)

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

From SyncLinear.com | NEXT-1308

ssijak avatar Jun 09 '23 12:06 ssijak

This PR https://github.com/vercel/next.js/pull/50406 seems like it should have fixed this issue, but I see the problem in my repro repositories

ssijak avatar Jun 09 '23 12:06 ssijak

CSS modules seem to be working ok. Removed vanilla-extract from this repro, and imported the same CSS from CSS module in the page and layout, and set it on the <button>, and it imports the CSS once.

Edit: it works like that if both the page and layout are RSC. When I use use client directive on the page it imports the same CSS twice https://share.cleanshot.com/HjhMJhCy

ssijak avatar Jun 09 '23 13:06 ssijak

This issue is still present in the latest canary (13.4.7-canary.1)

  1. Same styles are imported multiple times
  2. The order of imports is not deterministic

Here is a minimal repro with easy-to-reproduce test cases.

https://codesandbox.io/p/sandbox/next-51030-hlj722?file=%2Fapp%2Fpage.tsx%3A1%2C1

igordanchenko avatar Jun 20 '23 14:06 igordanchenko

The current order of imports wreaks havoc when CSS Cascade Layers are being used. The defined layer precedence that belongs in the root layout file gets read after the application of layers in child components. This causes the defined layer precedence to be ignored in favor of something random (https://css-tricks.com/css-cascade-layers/#aa-establishing-a-layer-order), and can make routes unusable.

This issue surfaced for me when updating up from 13.4.4 to 13.4.5 or 13.4.6.

tinleym avatar Jun 21 '23 16:06 tinleym

One workaround I'm currently using is to make the children CSS more specific: button.button instead of .button or div.something instead of .something.

ddoan avatar Jun 22 '23 12:06 ddoan

For https://codesandbox.io/p/sandbox/next-51030-hlj722?file=%2Fapp%2Fpage.tsx%3A1%2C1, it becomes very tricky if your CSS code itself has conflicts and some behaviors are undefined. For example when a dynamic component has loaded, its CSS might cause side effects to other parts of the page, which is expected.

For example, if you have a layout like this:

import style1 from 'a.module.css'
import style2 from 'b.module.css'

<button className={style1.btn + ' ' + style2.btn}>

The styles that imports later will override previous ones, so b.module.css will take precedence. However, if we have a page component that imports a.module.css again, it will take precedence over b.module.css again because page's styles have higher priority than the layout's. This is also a cause of duplicated styles.

In general, we recommend you to use CSS @layer, or try to make CSS selectors as pure and specific as possible.

shuding avatar Jun 23 '23 23:06 shuding

@shuding, I appreciate you taking the time to look into this example.

it becomes very tricky if your CSS code itself has conflicts and some behaviors are undefined.

I wouldn't call styles override a conflict. Overriding base component styles in a descendant component is a pretty common technique. Isn't that what "C" in CSS stands for?

For example when a dynamic component has loaded, its CSS might cause side effects to other parts of the page, which is expected.

The above example is a module-scoped CSS that doesn't have any global side-effects.

The styles that imports later will override previous ones, so b.module.css will take precedence.

Yes, you are absolutely correct, and that's the desired behavior that we are unfortunately not able to achieve under the app router.

However, if we have a page component that imports a.module.css again, it will take precedence over b.module.css again because page's styles have higher priority than the layout's. This is also a cause of duplicated styles.

In theory, yes. But it's not the case in the above example, isn't it?

igordanchenko avatar Jun 24 '23 01:06 igordanchenko

@shuding if you'll please read my comment below, @layer is not working.

The indeterministic order of imports wreaks havoc when CSS Cascade Layers are being used. The defined layer precedence that belongs in the root layout file gets read after the application of layers in child components. This causes the defined layer precedence to be ignored in favor of something random (https://css-tricks.com/css-cascade-layers/#aa-establishing-a-layer-order), and can make routes unusable.

This issue surfaced for me when updating up from 13.4.4 to 13.4.5 or 13.4.6.

tinleym avatar Jun 24 '23 01:06 tinleym

Thanks! I'll go through all the reproductions and think about an improvement in the next couple of days!

I understand that the confusion caused by the new architecture. In general scoped CSS itself doesn't have conflicts, but the order and duplication might cause the styles to conflict (override each other). I'll give you an example:

layout:

If the module that contains the .btn class is imported lastly, it will override the styles defined in .base. If only layout is rendered, that's the expected behavior.

However when page is rendered, page.css will be loaded and it has only .base. This CSS file will occur after layout.css and override the .btn styles in that file.

Previously in the pages directory, all styles will be packed into one CSS file. But here we need to generate one CSS per layout and page because they can be loaded separately.

That said, we still have some ideas to improve it. Like changing the CSS modules hashing algorithm to make it base on the layer, or deduplicate styles that are already in its parent layer. Will keep you updated in this issue.

shuding avatar Jun 24 '23 23:06 shuding

That said, we still have some ideas to improve it. Like changing the CSS modules hashing algorithm to make it base on the layer, or deduplicate styles that are already in its parent layer.

If I understand the latter suggestion correctly, this seems to me like the right approach. If a build system produces hashed rule/class names based on the rule contents (e.g., ._129ac00b) in layout.css, it'd be unnecessary to duplicate that rule in page.css, and that duplication causes the unexpected precedence fighting. The basic idea here would be if (selector in layout.css) strip from page.css. Although I say that with that big caveat that I don't know the implications when overriding a rule generated in page.css that's intentional and how to signify that.

To your point, if there's perfect purity, this won't be a problem, but it's also reasonably unrealistic that there wouldn't be things like rules applied to descendent selectors (and probably some non-negigible number of other scenarios) on class names that have a high likelihood of their precedence being trumped by the same properties in a rule duplicated in page.css.

boatilus avatar Jul 18 '23 00:07 boatilus

I'm also encountering the same behaviour.

For my use case, I'm creating standard UI/layout components that I want to use across multiple pages and components – these components have *.module.css styles. This allows me to add default custom stylings to these UI components and only load them if the component is used on the page. I also allow an additional className to be added for additional styling at a per-component level.

The problem is, as mentioned above, changing between routes/different app runs can result in different CSS load orders in addition to a huge amount of duplicate CSS.

For example:

// components/layout/Section.tsx

import styles from '../../styles/layout/Section.module.css';

interface Props extends React.ComponentProps<'section'> {
	fullWidth?: boolean;
}

export default function Section(props: Props) {
	const { fullWidth, ...remainingProps } = props;
	return (
		<section
			{...remainingProps}
			className={[styles['section'], props.className].join(' ')}
			data-fullwidth={fullWidth}
		>
			{props.children}
		</section>
	);
}

Navigating from Page A, to Page B, back to Page A cause Page A to display differently the second time round. Refreshing manually causes Page A to revert to its original layout.

For now, as a partial fix, I have managed to use css @layer to lower the CSS specificity of all the UI components' styles, however it still results in large amounts of duplicate css being added to each page, especially if the UI component is used frequently (such as a custom button).

Would be interested to know if there is a better way to go about this. I can provide more detailed examples/reproductions if necessary.

sleepdotexe avatar Jul 18 '23 06:07 sleepdotexe

@tinleym

The current order of imports wreaks havoc when CSS Cascade Layers are being used. The defined layer precedence that belongs in the root layout file gets read after the application of layers in child components. This causes the defined layer precedence to be ignored in favor of something random (https://css-tricks.com/css-cascade-layers/#aa-establishing-a-layer-order), and can make routes unusable.

This issue surfaced for me when updating up from 13.4.4 to 13.4.5 or 13.4.6.

Have a quick hack fix for the css layer order here https://github.com/vercel/next.js/issues/16630#issuecomment-1644918877

jep-a avatar Jul 21 '23 03:07 jep-a

Is there already a solution for css that is loaded multiple times if you use the "use client" mode? I use css modules and have f.e. several buttons or inputs on 1 page. The css (modules) are loaded multiple times in version 13.4.19.

katiasmet-93 avatar Aug 28 '23 07:08 katiasmet-93

Is there a way to consolidate all styles into one file, so that the minifier automatically removes duplicates? I can't estimate the scale of the issue in kilobytes, but I see that each of my components (a total of 31) duplicates styles three times, and this is in production.

Screenshot 2023-09-05 at 01 37 57

monolithed avatar Sep 04 '23 18:09 monolithed

I just ended up writing a simple Webpack plugin that removes duplicate rules by their class names (which isn't a good idea in pratice, but has worked well enough for my needs). I've only tested this with CSS generated with Vanilla Extract, and it doesn't support route groups, but someone may find it useful.

boatilus avatar Sep 05 '23 12:09 boatilus

I have the same problems and it's awful. My app is very fragile. It happens when I navigate through pages containing common components.

Screenshot 2023-09-08 at 01 24 15

Stillonov avatar Sep 07 '23 22:09 Stillonov

Maybe not the best solution for now, but converting to the pages router fixed it for me.

katiasmet-93 avatar Sep 08 '23 06:09 katiasmet-93

Maybe not the best solution for now, but converting to the pages router fixed it for me.

@katiasmet-93, your solution might be suitable for projects with a small codebase where there's no need for testing investments. But such thoughts really make one reconsider completely dropping Next.

monolithed avatar Sep 08 '23 06:09 monolithed

I have the same problem when using shared components in layouts and pages (next 13.4.19). It doesn't work correctly both when using CSS modules and when using tailwind.

nikita2090 avatar Sep 12 '23 09:09 nikita2090

Same issue with mantine https://github.com/vercel/next.js/issues/16630#issuecomment-1718974809

olalonde avatar Sep 14 '23 09:09 olalonde

Same problem on 13.5.2 not the ideal solution but downgrade to 13.4.4 helped me.

gffuma avatar Sep 21 '23 09:09 gffuma

Same problem on 13.5.2 not the ideal solution but downgrade to 13.4.4 helped me.

Screenshot 2023-09-22 at 19 04 29

@gffuma, I tried downgrading to version 3.4, and it didn't help at all. If the component is not being reused, there are no issues.

monolithed avatar Sep 22 '23 11:09 monolithed

Is exact the 3.4.4 ?

gffuma avatar Sep 22 '23 12:09 gffuma

Is exact the 3.4.4 ?

@dgagn, yep! I tried that version. I don't think any magic should happen because this bug has been around for more than three years

monolithed avatar Sep 22 '23 13:09 monolithed

Most likely I have the same problem ((

270266163-017fb489-cd28-400c-b812-967444e140e0 270264894-b1b696ef-c3a4-46e4-b01c-2438ad7ed090

ensidialabs avatar Sep 27 '23 06:09 ensidialabs

The multiple imports also causes animation issues. If you want, say, a no-js fade in for a module on a dedicated route, a CSS module with an animate property could get reapplied during the animation and cause it to repeat.

tinleym avatar Oct 22 '23 16:10 tinleym

Using 14.0.1

Screenshot 2023-11-02 at 11 07 16

maiconsanson avatar Nov 02 '23 14:11 maiconsanson

Just chiming in to say I'm seeing the same as the above on 14.0.2 - hadn't noticed it previously when on 13.5.3, might look to revert back and see if it was the same

Screenshot 2023-11-15 at 13 17 29

From what I can tell, if there's a 'use client' somewhere in the imports of a page/component, then things start to go a bit whacky, and things start doubling up on CSS

cpotey avatar Nov 15 '23 12:11 cpotey

Let's assume that we are going to use @layer. When we are using a library, for example react-quill in my case, which has its own class names for styling, their class names will take precedence over our custom one and over ride them, there is no way to over ride them without !important. Is there a way out of this? @shuding

sjahanmard avatar Nov 27 '23 15:11 sjahanmard

For css from libraries, the only workaround I found is to rewrite it by encapsulating it in a @layer @sjahanmard

For defining @layer, I use this workaround: https://github.com/vercel/next.js/issues/51030#issuecomment-1644922285

After all this, despite the duplication of the CSS, everything is ok I'm using version 13.4.7

tomjvdps avatar Dec 22 '23 18:12 tomjvdps