在 Svelte 中使用 CSS-in-JS

你即使不须要,但你能够。

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

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

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

这即是为什么 Svelte 容许你在组件的 <style> 标签中添加 CSS 的缘故。java

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

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

这些是咱们计划在将来版本中解决的,不过与此同时,若是你亟需这些功能的话,你能够使用与框架无关的 CSS-in-JS 库。性能

示例

在这里,咱们用 Emotion 来生成能够跨多个组件中使用的范围受限的类名:优化

App.sveltespa

<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.sveltecode

<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 处理二者一块儿使用。


< The End >

​- 窗明几净,静候时日变迁 -

相关文章
相关标签/搜索