在 Svelte 中使用 CSS-in-JS

你即便不需要,但你可以。

注意:原文发表于2018-12-26,随着框架不断演进,部分内容可能已不适用。

CSS 是任何 Web 应用程序的核心部分。

宽泛而论,如果一个 UI 框架没有内置向组件添加样式的方式,那么它就是半成品。

这便是为何 Svelte 允许你在组件的 <style> 标签中添加 CSS 的缘故。

将 CSS 与标记共存,意味着我们可以解决开发人员在编写 CSS 时遇到的最大问题,在不引入新的问题的同时,还提供极佳的开发体验。

但是 Svelte 的样式处理确实存在一些限制,在组件之间共享样式或者应用级优化都艰难重重。

这些是我们计划在未来版本中解决的,不过与此同时,如果你亟需这些功能的话,你可以使用与框架无关的 CSS-in-JS 库。

示例

在这里,我们用 Emotion 来生成可以跨多个组件中使用的范围受限的类名:

App.svelte

<script>
  import { comicSans, link } from './styles.js';
  import Hero from './Hero.svelte';
</script>
​
<Hero/>
​
<div class={comicSans}>
  <p>
    Did you enjoy your lunch, mom? You drank it fast enough. 
    I know, I just call her Annabelle cause she's shaped like a…
    she's the belle of the ball! YOU'RE the Chiclet! Not me. 
    Caw ca caw, caw ca caw, caw ca caw! 
    A Colombian cartel that WON'T kidnap and kill you. 
    You go buy a tape recorder and record yourself for a whole day. 
  <a class={link} href="https://bluthipsum.com/">I think you'll be surprised at some of your phrasing.</a>
  </p>
</div>

Hero.svelte

<script>
  import { title, comicSans, box } from './styles.js';
</script>
​
<div class="{title} {comicSans}">
  <h1>
    <div class={box}>
      <div class={box}>
        <div class={box}>CSS</div>
        in JS
      </div>
      in HTML
    </div>
  </h1>
</div>

styles.js

import emotion from 'emotion/dist/emotion.umd.min.js';
​
const { css } = emotion;
​
const brand = '#74D900';
​
export const title = css`
  color: ${brand};
  font-size: 1em;
  white-space: nowrap;
`;
​
export const comicSans = css`
  font-family: 'Comic Sans MS', cursive;
`;
​
export const box = css`
  position: relative;
  display: inline-block;
  border: 2px solid ${brand};
  line-height: 1;
  padding: 4px;
  border-radius: 4px;
`;
​
export const link = css`
  color: inherit;
  font-weight: bold;
  text-decoration: none;
  border-bottom: 1px solid ${brand};
  &:hover {
    text-decoration: none;
    background: ${brand};
  }
`;

不过一定要提醒你的是,大多数的 CSS-in-JS 库都有一个运行时,许多库在构建时,不支持将样式静态提取到单独的 .css 文件中(这对于获取最佳性能至关重要)。

因此,仅在你的应用有迫切需要时才建议使用 CSS-in-JS!

请注意,你也可以混合搭配 CSS-in-JS 和 Svelte 内置的 CSS 处理两者一起使用。


posted @ 2021-02-21 23:29  前端子鱼  阅读(190)  评论(0编辑  收藏  举报