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.
First, you need to install the styled-components plugin dependency:
npm install @modern-js/plugin-styled-components -DThen configure the styled-components plugin in modern.config.ts:
import { defineConfig } from '@modern-js/app-tools';
import { styledComponentsPlugin } from '@modern-js/plugin-styled-components';
export default defineConfig({
plugins: [
styledComponentsPlugin({
// ...
displayName: true,
minify: process.env.NODE_ENV === 'production',
}),
],
});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.
When you need to write a div component with red text inside, you can implement it as follows:
import styled from '@modern-js/plugin-styled-components/styled';
const RedDiv = styled.div`
color: red;
`;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:
import styled from '@modern-js/plugin-styled-components/styled';
const Button = styled.button`
color: ${props => (props.primary ? 'white' : 'red')};
font-size: 1em;
`;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.