css-in-js是一种在js中处理css的方式,目的是让css更好地和js整合起来。 这篇文章的初衷是调查如何更好在react中编写css。
关于css-in-js
一篇介绍文章:https://www.freecodecamp.org/news/how-to-style-react-apps-with-css/,其中列举了集中在js中联合使用css的方式:
- Inline Styles
- HTML原生
- Plain CSS
- HTML原生
- SASS / SCSS
- 需要借助预处理器,主要是为了给CSS引入变量、模板等特性
- 此外还有PostCSS
- CSS Modules
- 需要借助预处理器,主要是为了模块化CSS,也就是对命名上进行隔离
- CSS-in-JS
- 需要借助预处理器,或者在运行时依靠JS自身的处理
其他介绍文章:
著名的css-in-js料库有哪些
比较经典的当属styled-components。
其他料库
- https://compiledcssinjs.com/,Atlassian出品,仅支持react
- 貌似不支持自动theme切换
- https://vanilla-extract.style/,Zero-runtime Stylesheets in TypeScript
- https://linaria.dev, Zero-runtime CSS in JS library
- https://github.com/andreipfeiffer/css-in-js/blob/main/README.md#styled-jsx,在JSX中支持类似HTML中的
<style>
标签
css-in-js料库列表
- https://michelebertoli.github.io/css-in-js/
- The CSS-in-React Landscape,同时也介绍几款css-in-js料库
- A Thorough Analysis of CSS-in-JS
在react中使用emotion-js
在react项目中安装emotion相关料包:
yarn add @emotion/react
vscode中emotion的语法着色可以使用vscode-styled-components
扩展。
在vite创建的项目中配置emotion可以参考https://dev.to/glocore/configure-emotion-with-your-vite-react-project-7jl,需要安装babel-plugin
yarn add -D @emotion/babel-plugin
然后更新vite.config.js
如下:
export default defaultConfig({
plugins: [
react({
jsxImportSource: "@emotin/react",
babel: {
plugins: ["@emotion/bable-plugin"]
}
})
]
})
开启typescript支持,需要在tsconfig.json中设置:
{
"compilerOptions": {
"jsxImportSource": "@emotion/react"
}
}
其他参考:https://blog.csdn.net/u012961419/article/details/117216004
(本篇完)