gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.3k stars 10.31k forks source link

Inconsistent order of CSS rules between dev and build #39076

Open receter opened 3 months ago

receter commented 3 months ago

Preliminary Checks

Description

When I run gatsby develop the order of CSS classes is as expected. When building the CSS order appears to be different in some cases.

I expect that CSS Module files that are imported earlier will appear before classes from CSS Module files that are imported later.

In my reproduction example this is not the case after building. One CSS class that is imported late, appears too early in the CSS.

If you run npm run start you will see this:

dev

If you run npm run build && npx serve public you will see this instead:

build

This might be related to a CSS Module file that is imported inside an example component library package in node_modules.

Reproduction Link

https://github.com/receter/gatsby-css-order-issue

Steps to Reproduce

Clone https://github.com/receter/gatsby-css-order-issue Run dev server: The text is blue Build and serve: The text is black

Expected Result

The text should be blue

Actual Result

The text is black when built

Environment

System:
    OS: macOS 14.6.1
    CPU: (10) arm64 Apple M1 Pro
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.20.4 - ~/.nvm/versions/node/v18.20.4/bin/node
    npm: 10.8.3 - ~/.nvm/versions/node/v18.20.4/bin/npm
  Languages:
    Python: 3.11.4 - /opt/homebrew/opt/python@3.11/libexec/bin/python
  Browsers:
    Chrome: 128.0.6613.114
    Safari: 17.6
  npmPackages:
    gatsby: ^5.13.7 => 5.13.7
    gatsby-cli: ^5.13.3 => 5.13.3
    gatsby-css-order-issue-package: ^1.0.0 => 1.0.0
  npmGlobalPackages:
    gatsby-css-order-issue-package: 1.0.0

Config Flags

No response

receter commented 3 months ago

I just found out that removing side effects in the external package's package.json does fix this issue. And I think (but I am not 100% sure) that in case of importing CSS Modules (like import * as styles from "x.module.css"), marking them as side effects is not necessary.

  "sideEffects": [
    "**/*.css"
  ],

But the issue still kind of persists if I switch from using CSS Modules to normal CSS because in this case I think I should not remove the side effect marking from the package.json.

Having said that removing sideEffects will also fix the issue here because the bundler well not tree shake the module if sideEffects is not defined in package.json.

This might be related:

https://github.com/webpack-contrib/mini-css-extract-plugin/issues/1070 https://github.com/webpack/webpack/issues/7094