
npm install --save @stylexjs/stylex
Vite
npm install --save-dev vite-plugin-stylex
Vite 플러그인은 2024-02-07 기준 미완성 이어서 불안정함
vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import styleX from 'vite-plugin-stylex';
export default defineConfig({
plugins: [react(), styleX()],
});
<div {...stylex.props(styles.base)} />
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
base: {
fontSize: 16,
lineHeight: 1.5,
color: 'grey',
},
highlighted: {
color: 'rebeccapurple',
},
});
<div {...stylex.props(styles.base, styles.highlighted)} />;
나중에 쓰인 highlighted의 color가 적용 됨
<div
{...stylex.props(
styles.base,
props.isHighlighted && styles.highlighted,
isActive ? styles.active : styles.inactive,
)}
/>
import { InputField } from '../../../components/Form/InputField';
import * as stylex from '@stylexjs/stylex';
import * as React from 'react';
const styles = stylex.create({
dark: {
backgroundColor: 'black',
color: 'white',
},
light: {
backgroundColor: 'white',
color: 'black',
},
});
export const LoginForm = () => {
const [mode, setMode] = React.useState<'light' | 'dark'>('light');
const toggleMode = () => {
// 모드를 전환하는 함수
setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));
};
return (
<>
<InputField type="password" style={[styles[mode]]} />
<button onClick={toggleMode}>Toggle Mode</button>
</>
);
};
이런식으로 가능하나
@media (prefers-color-scheme: dark)를 사용하면 JavaScript 없이 CSS만으로 모드를 전환할 수 있어서 렌더링 성능을 향상시킬 수 있음,
StyleX에서도 키프레임이나 미디어 쿼리가 가능함.
<CustomComponent style={styles.base} />
[!warning]
Thestylex.propsfunctions returns an object withclassNameandstyle. Don't use it when the styles are to be merged within a component.// NO! <CustomComponent style={stylex.props(styles.base)} />
// InputField.tsx
import * as stylex from '@stylexjs/stylex';
import { StyleXStyles } from '@stylexjs/stylex';
interface InputFieldProps {
type?: 'text' | 'email' | 'password';
style?: StyleXStyles;
}
export const InputField = (props: InputFieldProps) => {
// default = text
const { type = 'text', style } = props;
return <input type={type} {...stylex.props(style)}></input>;
};
// LoginForm.tsx
import { InputField } from '../../../components/Form/InputField';
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
foo: {
color: 'red',
fontSize: '2em',
},
bar: {
backgroundColor: 'blue',
},
});
export const LoginForm = () => {
return (
<>
<InputField type="password" style={[styles.foo, styles.bar]} />
<h1 {...stylex.props(styles.foo, styles.bar)}>asdf</h1>
</>
);
};
그러나 이렇게 커스텀 컴포넌트를 사용하면 StyleX의 이점인 CSS를 자동으로 생성하고 관리를 못 함. 왜냐면 자바스크립트가 런타입 중에 객체를 옮겨서 확인해야하기 때문에.
stylex.create 호출뿐만 아니라 가능한 경우 stylex.props 호출도 컴파일 시간에 제거되기 때문입니다.stylex.create 호출은 완전히 삭제되지 않고, 대신 키를 클래스 이름에 매핑하는 객체를 남깁니다. 그리고 stylex.props() 호출은 런타임에 실행됩니다.그렇지만 stylex.props()함수는 속도가 빠르기 때문에 런타임 비용은 최소화가 되긴 함
<InputField type="password" style={[styles.variants, styles.size]} />
<input type="password" {...stylex.props(styles.variants, styles.size)}></input>
둘은 차이가 있음.
유지보수성과 재사용성을 높이려면 위의 방법
유지보수성과 재사용성은 떨어지지만 성능면에서는 아래의 방법
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
base: {
color: null,
},
});
null로 하게되면 적용한 스타일이 제거가 된다.