Css In Js
2023年12月18日
一、认识
社区中有两款主流的 CSS In JS
方案: styled-components
和emotion
。 对于 CSS In JS
方案,在构建侧我们需要考虑选择器命名问题、DCE
(Dead Code Elimination
即无用代码删除)、代码压缩、生成 SourceMap
、服务端渲染(SSR
)等问题,而styled-components
和emotion
已经提供了对应的 babel
插件来解决这些问题,我们在 Vite
中要做的就是集成这些 babel
插件。
二、配置
具体来说,上述的两种主流 CSS in JS
方案在 Vite
中集成方式如下:
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react({
babel: {
// 加入 babel 插件
// 以下插件包都需要提前安装
// 当然,通过这个配置你也可以添加其它的 Babel 插件
plugins: [
// 适配 styled-component
"babel-plugin-styled-components"
// 适配 emotion
"@emotion/babel-plugin"
]
},
// 注意: 对于 emotion,需要单独加上这个配置
// 通过 `@emotion/react` 包编译 emotion 中的特殊 jsx 语法
jsxImportSource: "@emotion/react"
})
]
})