使用 CSS-in-JS
CSS-in-JS 是一种可以将 CSS 样式写在 JS 文件里的技术。
Modern.js 支持社区常用的 CSS-in-JS 实现库 styled-components,它使用 JavaScript 的新特性 Tagged template 编写组件的 CSS 样式。
Modern.js 插件 @modern-js/plugin-styled-components 提供了对 styled-components 的支持,并为 styled-components 添加了服务器端渲染能力。你可以通过安装 @modern-js/plugin-styled-components 插件来使用 styled-components。
在 Modern.js 中使用 styled-components
首先,你需要安装 styled-components 插件依赖和 styled-components 库:
然后在 modern.config.ts 中配置 styled-components 插件:
styledComponentsPlugin 插件的配置项与 @rsbuild/plugin-styled-components 插件的配置项相同,你可以参考 @rsbuild/plugin-styled-components 插件的文档进行配置。
使用 styled-components 编写样式
当需要编写一个内部字体为红色的 div 组件时,可以如下实现:
当需要根据组件的 props 动态设置组件样式时,例如 props 的属性 primary 为 true 时,按钮的颜色为白色,其他情况为红色,实现代码如下:
关于 styled-components 的更多用法,请参考 styled-components 官网。
如果需要使用 styled-jsx、Emotion 等其他 CSS-in-JS 库,需要先安装对应库的依赖。具体使用方式请参考对应库的官网。