Using CSS-in-JS

CSS-in-JS is a technique that allows you to write CSS styles in JS files.

Modern.js integrates the popular CSS-in-JS implementation library styled-components, which uses the new JavaScript feature Tagged template to write component CSS styles. You can directly import the API of styled-components from @modern-js/runtime/styled for use.

When you need to write a div component with an internal font color of red, you can implement it as follows:

import styled from '@modern-js/runtime/styled';

const RedDiv = styled.div`
  color: red;
`;

If you need to dynamically set component styles based on the component's props, for example, the primary property of props is true, the button color is white, otherwise it is red, you can implement the code as follows:

import styled from '@modern-js/runtime/styled';

const Button = styled.button`
  color: ${props => (props.primary ? 'white' : 'red')};
  font-size: 1em;
`;

For more usage of styled-components, please refer to styled-components official website.

Modern.js integrates Babel's babel-plugin-styled-components plugin internally, and you can configure the plugin through tools.styledComponents.

TIP

If you need to use other CSS-in-JS libraries such as styled-jsx and Emotion, you need to install the corresponding dependencies first. For specific usage, please refer to the library's official website.