sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.96k stars 4.25k forks source link

Svelte 5: add $style and CSS modules support (like Vue) to fully obfuscate/isolate class names #9999

Open dm-de opened 10 months ago

dm-de commented 10 months ago

Describe the problem

First... Vue has this functionality - I miss in Svelte https://vuejs.org/api/sfc-css-features.html#css-modules https://github.com/vitejs/vite/discussions/7447#discussioncomment-4128874

Code like this in Svelte:

<h1 class:block={true}>Hello</h1>
<style>
    .block { display: block; }
</style>

will generate such CSS: .block.svelte-3zrlxr{display:block}

.block is my own custom class name .svelte-3zrlxr is auto-generated class name for whole component

But this is not enough! This was a "cheap" solution, that have side effects! Today... custom class names (like block) can collide with GLOBAL class names. This means, that custom used classes are simple not isolated!

Describe the proposed solution

Svelte like solution. Example code: (module was added to not break compatibility)

<h1 class={$style.block}>Text</h1>
<style module>
  .block { display: block; }
</style>

or convert (auto obfuscate)

<h1 class:block={true}>Text</h1>
<style module>
  .block { display: block; }
</style>

Both should be possible

Alternatives considered

CSS-modules work today. They obfuscate class names. Vite support CSS modules: https://vitejs.dev/guide/features#css-modules

If i write code like this, it works:

<script>
    import style from './style.module.css'
</script>
<h1 class={style.block}>Text</h1>

It generate this class name for "block": _block_1xra7_1

But now, I need to split component in separate files. I search a way to use