# Stylex
https://stylex-docusaurus.vercel.app/docs/
一套 css-in-js 的工具,本身是透過 `runtime` 編譯 `css`,而不是 css 得預處理器,所有頁面用到的 `css` 都是在 `runtime` 運行時產生,不像之前的 sass 或是 tailwindcss 會有 preload css 的步驟,別於以往的 css-in-js 使用例如styled-components ,是宣告一個 component 方式,stylex 則是應用在 inline style 上,原因很簡單因為 stylex 的定位是一個 css-in-js 的用法,而不是侷限在 css-in-react 身上,下面簡單介紹 stylex 優點。
1. 可讀性極高 : 寫法很像 RN 的 styled 方式,讓你的 style 命名有意義。
```typescript
import stylex from '@stylexjs/stylex';
const styles = stylex.create({
base: {
fontSize: 16,
lineHeight: 1.5,
color: 'rgb(60,60,60)',
},
highlighted: {
color: 'rebeccapurple',
},
});
```
```typescript
<div className={stylex(styles.base,styles.highlighted)} />
// OR
<div {...stylex.spread(styles.base,styles.highlighted)} />
```
2. 強大的 design system : stylex 是一套透過 css 變數來使用 css ,所以提供很多 api 讓你共同管理 css 邏輯,架構用起來會比較穩定,DX 體驗也會比較好,簡單舉例幾個 api。
### Fallback Styles
css styled 兼容性
```typescript
import stylex from '@stylexjs/stylex';
const styles = stylex.create({
header: {
position: stylex.firstThatWorks('sticky', '-webkit-sticky', 'fixed'),
},
});
```
等於
```typescript
.header {
position: fixed;
position: -webkit-sticky;
position: sticky;
}
```
## css variable
```typescript
// declare variable
import stylex from '@stylexjs/stylex';
// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';
export const colors = stylex.createVars({
primaryText: {default: 'black', [DARK]: 'white'},
secondaryText: {default: '#333', [DARK]: '#ccc'},
accent: {default: 'blue', [DARK]: 'lightblue'},
background: {default: 'white', [DARK]: 'black'},
lineColor: {default: 'gray', [DARK]: 'lightgray'},
borderRadius: '4px',
fontFamily: 'system-ui, sans-serif',
fontSize: '16px',
});
// use variable
import stylex from '@stylexjs/stylex';
import {colors, spacing} from '../tokens.styles';
const styles = stylex.create({
container: {
color: colors.primaryText,
backgroundColor: colors.background,
padding: spacing.medium,
},
});
```
3. 減少 css 體積:因為 `stylex` 不是 `css `預處理器 ,所以初始化時要載入的 css 會大大減少,這邊簡單補充一個目前的 css library 遇到的問題,隨著專案變大整體 css 樣式內容變多,容易造成 initial load css 的效能問題<,大部分廠通常會採取 splittind css 方式優化 initial load ,但這樣會有一個 recalculate styles 的問題,每次都會需要重新 update css 內容,更新樣式會有延遲,但 `stylex` 的做法比較不一樣的地方是,他採用 all css in one file 作法,但優化的是optimizing CSS bundle size 的結果。
4. type safe : `stylex` 會了考量樣式的 type ,追蹤採用 Flow (強型別語言)去自動化產生 type。
## 總結
蠻推薦大型專案上去使用的,原因是 `極高的可維護性` 跟 `性能上的優化 ( 減少 css bundle size 與優化 initial load)` ,但如果是小專案可能會看不太出來效能優勢,但有些 api 還蠻實用的就是XD,最後其實也蠻推薦用 `stylex` 去開發 npm package ,因為他有強大的 `type safe` 的做用,甚至方便透過 `props` 傳入樣式~