Svelte组件中的CSS类可能会被意外覆盖。

huangapple go评论55阅读模式
英文:

CSS classes in Svelte components could be accidentally overwritten

问题

Svelte支持作用域CSS,这意味着如果有一个类名,会添加一个额外的生成类名。例如:

<div class="item"></div>

会被转换成:

<div class="item item-poYXsoYvx1uy"></div>

并且样式将被应用为.item.item-poYXsoYvx1uy以增加特异性。这是有益的。

但是想象一下,你正在使用Svelte构建一个小组件,并将其嵌入到某个页面中,而该页面上也使用了类名item。这可能会轻松干扰你的小组件并破坏样式。

我更希望在生产构建中根本不保留初始类名,只保留散列类名。这是否可能?

英文:

Svelte has support for scoped CSS, means if there is a class, one more generated class will be added. For example:

&lt;div class=&quot;item&quot;&gt;&lt;/div&gt;

will be transformed:

&lt;div class=&quot;item item-poYXsoYvx1uy&quot;&gt;&lt;/div&gt;

and styles will be applied as .item.item-poYXsoYvx1uy to increase specificity. It's good.

But imagine you building a widget using Svelte and embed it to some page where the class name item used as well. It could easily interfere with your widget and brake styling.

I'd prefer not to have initial class names at all in the production build, just with hash ones. Is it possible?

答案1

得分: 1

你可以直接使用标签名称来定位元素,但这不会让你走得很远。

在与未经范围限定的样式一起使用组件可能会引发问题的情况下,我建议给类名加上前缀。

例如,使用.sc-item(代表"Svelte组件")或类似/更独特的名称。

英文:

You can target elements directly using the tag name but that will not get you very far.

In a scenario where a component is used together with unscoped styles that could cause issues, I would recommend prefixing classes.

E.g. use .sc-item (for "Svelte component") or something similar/more unique.

huangapple
  • 本文由 发表于 2023年6月18日 23:45:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定