sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
77.46k stars 4.04k forks source link

Imported global styles apply differently in dev and build mode #12168

Open samlfair opened 1 week ago

samlfair commented 1 week ago

Describe the bug

Of course we expect global styles to apply globally:

https://github.com/sveltejs/svelte/issues/11990

There's some confusion about when a global style will get applied. For example, you might not expect a global style to be applied just because you import a component or include it in your $lib/components/index.js.

But what if the component isn't meant to get imported?

Rich Harris gave an example for how to import components dynamically:

https://github.com/sveltejs/kit/issues/9775#issuecomment-1526147626

This includes a dynamic import:

    for (const block of blocks) {
        components[block.type] = await import(`$lib/blocks/${block.type}.svelte`);
    }

If you include global styles in these components, they will get applied differently in development and build mode.

In dev mode, only the global styles that apply are the ones that actually get imported.

image

In build mode, all global styles that could get imported are applied:

image

I would argue that the former is the expected behavior. Why would you expect styles to get applied for a component that is never imported?

This makes handling components with global styles quite frustrating. Effectively, any global style that you declare in your project might get applied regardless of whether or not you use the component. Even global styles in components that aren't imported might get applied.

The ability to dynamically load global CSS is a common question:

https://github.com/sveltejs/kit/issues/9943

Dynamic component imports with global styles offer a promising workaround, but only with the current dev mode behavior. The build mode behavior instead introduces a significant liability to using global styles.

Reproduction

https://stackblitz.com/edit/sveltejs-kit-template-default-wbbtp2?file=src%2Froutes%2F%2Bpage.js

Logs

No response

System Info

System:
    OS: macOS 14.4.1
    CPU: (8) x64 Apple M1 Pro
    Memory: 30.84 MB / 16.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 18.18.0 - ~/.nvm/versions/node/v18.18.0/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.8.1 - ~/.nvm/versions/node/v18.18.0/bin/npm
    pnpm: 8.15.0 - ~/.nvm/versions/node/v18.18.0/bin/pnpm
    bun: 1.1.4 - ~/.bun/bin/bun
  Browsers:
    Chrome: 126.0.6478.63
    Safari: 17.4.1
  npmPackages:
    svelte: ^5.0.0-next.1 => 5.0.0-next.165

Severity

blocking an upgrade

samlfair commented 1 week ago

(Sorry I recognize I posted this in the wrong repo. Please let me know if I should move.)