Using CSS-in-JS
CSS-in-JS is a technique that allows you to write CSS styles within JS files.
Modern.js supports the commonly used community CSS-in-JS library styled-components, which uses JavaScript's new feature Tagged template to write component CSS styles.
The Modern.js plugin @modern-js/plugin-styled-components provides support for styled-components and adds server-side rendering capability for styled-components. You can use styled-components by installing the @modern-js/plugin-styled-components plugin.
Using styled-components in Modern.js
First, you need to install the styled-components plugin dependency and the styled-components library:
Then configure the styled-components plugin in modern.config.ts:
The configuration options of the styledComponentsPlugin plugin are the same as those of the @rsbuild/plugin-styled-components plugin. You can refer to the documentation of @rsbuild/plugin-styled-components for configuration.
Writing styles with styled-components
When you need to write a div component with red text inside, you can implement it as follows:
When you need to dynamically set component styles based on the component's props, for example, when the primary attribute of props is true, the button's color is white, otherwise red, the implementation is as follows:
For more usage of styled-components, please refer to the styled-components official website.
If you want to use other CSS-in-JS libraries such as styled-jsx, Emotion, etc., you need to install the corresponding dependencies first. Please refer to the official websites of the respective libraries for specific usage.