From 30d58ad6f648e670fda20d80306083db7d46fc94 Mon Sep 17 00:00:00 2001 From: zhangxiang Date: Tue, 18 Nov 2025 18:03:11 +0800 Subject: [PATCH 1/2] feat: add styled-components plugin options and fix docs --- .changeset/whole-numbers-visit.md | 6 + .../cli/plugin-styled-components/src/index.ts | 20 +- .../en/apis/app/runtime/utility/css-in-js.mdx | 5 +- .../docs/en/configure/app/tools/ts-loader.mdx | 4 +- .../en/guides/advanced-features/low-level.mdx | 19 +- .../guides/basic-features/css/css-in-js.mdx | 53 +-- .../en/guides/troubleshooting/builder.mdx | 14 - .../document/docs/en/plugin/introduction.mdx | 23 +- .../en/plugin/official/cli-plugins/_meta.json | 2 +- .../cli-plugins/plugin-styled-components.mdx | 5 + .../zh/apis/app/runtime/utility/css-in-js.mdx | 5 +- .../docs/zh/configure/app/tools/ts-loader.mdx | 4 +- .../zh/guides/advanced-features/low-level.mdx | 19 +- .../guides/basic-features/css/css-in-js.mdx | 36 +- .../zh/guides/troubleshooting/builder.mdx | 14 - .../document/docs/zh/plugin/introduction.mdx | 21 +- .../zh/plugin/official/cli-plugins/_meta.json | 2 +- .../cli-plugins/plugin-styled-components.mdx | 5 + .../docs/zh/tutorials/first-app/c03-css.mdx | 4 +- .../docs/en/tutorials/first-app/c03-css.mdx | 334 ++++++++++++++++++ .../fixtures/stream/modern.config.ts | 7 +- 21 files changed, 465 insertions(+), 137 deletions(-) create mode 100644 .changeset/whole-numbers-visit.md create mode 100644 packages/document/docs/en/plugin/official/cli-plugins/plugin-styled-components.mdx create mode 100644 packages/document/docs/zh/plugin/official/cli-plugins/plugin-styled-components.mdx create mode 100644 packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx diff --git a/.changeset/whole-numbers-visit.md b/.changeset/whole-numbers-visit.md new file mode 100644 index 000000000000..cf84c52b1744 --- /dev/null +++ b/.changeset/whole-numbers-visit.md @@ -0,0 +1,6 @@ +--- +'@modern-js/plugin-styled-components': patch +--- + +feat: add styled-components plugin options and fix docs +feat: styled-components 插件增加配置参数并修复相关文档 diff --git a/packages/cli/plugin-styled-components/src/index.ts b/packages/cli/plugin-styled-components/src/index.ts index d7ec62217e3f..99542e2b75cc 100644 --- a/packages/cli/plugin-styled-components/src/index.ts +++ b/packages/cli/plugin-styled-components/src/index.ts @@ -1,7 +1,12 @@ import type { AppTools, CliPlugin } from '@modern-js/app-tools'; -import { pluginStyledComponents } from '@rsbuild/plugin-styled-components'; +import { + type PluginStyledComponentsOptions, + pluginStyledComponents, +} from '@rsbuild/plugin-styled-components'; -export const styledComponentsPlugin = (): CliPlugin => ({ +export const styledComponentsPlugin = ( + options?: PluginStyledComponentsOptions, +): CliPlugin => ({ name: '@modern-js/plugin-styled-components', setup(api) { @@ -9,16 +14,11 @@ export const styledComponentsPlugin = (): CliPlugin => ({ return { builderPlugins: [ pluginStyledComponents({ - displayName: true, - minify: process.env.NODE_ENV === 'production', + ...options, + // https://github.com/styled-components/babel-plugin-styled-components/issues/287 + topLevelImportPaths: ['@modern-js/plugin-styled-components/styled'], }), ], - tools: { - // styledComponents: { - // // https://github.com/styled-components/babel-plugin-styled-components/issues/287 - // topLevelImportPaths: ['@modern-js/plugin-styled-components/styled'], - // }, - }, resolve: { alias: { 'styled-components': require.resolve('styled-components'), diff --git a/packages/document/docs/en/apis/app/runtime/utility/css-in-js.mdx b/packages/document/docs/en/apis/app/runtime/utility/css-in-js.mdx index 0197b9860afd..fd3a9b8e5fae 100644 --- a/packages/document/docs/en/apis/app/runtime/utility/css-in-js.mdx +++ b/packages/document/docs/en/apis/app/runtime/utility/css-in-js.mdx @@ -1,6 +1,7 @@ --- title: CSS-In-JS API --- + # CSS-In-JS API Use Style Component to write CSS. @@ -8,7 +9,7 @@ Use Style Component to write CSS. ## Usage ```ts -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; ``` ## Function Signature @@ -18,7 +19,7 @@ see [styled-component API](https://styled-components.com/docs/api). ## Example ```tsx -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; const Button = styled.button` background: palevioletred; diff --git a/packages/document/docs/en/configure/app/tools/ts-loader.mdx b/packages/document/docs/en/configure/app/tools/ts-loader.mdx index c5fed8a6a2bc..9401736700f4 100644 --- a/packages/document/docs/en/configure/app/tools/ts-loader.mdx +++ b/packages/document/docs/en/configure/app/tools/ts-loader.mdx @@ -6,7 +6,7 @@ title: tsLoader import { Badge } from '@theme'; -Webpack Only +Webpack Only - **Type:** `Object | Function | undefined` - **Default:** `undefined` @@ -15,7 +15,7 @@ import { Badge } from '@theme'; ts-loader is not recommended for use in the project, because: -- ts-loader cannot be used with certain features such as [source.transformImport](/configure/app/source/transform-import) and [tools.styledComponents](/configure/app/tools/styled-components) provided by Babel & SWC. +- ts-loader cannot be used with certain features such as [source.transformImport](/configure/app/source/transform-import)provided by Babel & SWC. - Rspack does not support ts-loader. ::: diff --git a/packages/document/docs/en/guides/advanced-features/low-level.mdx b/packages/document/docs/en/guides/advanced-features/low-level.mdx index 252fa9ff6713..89a750f5d26a 100644 --- a/packages/document/docs/en/guides/advanced-features/low-level.mdx +++ b/packages/document/docs/en/guides/advanced-features/low-level.mdx @@ -30,13 +30,12 @@ When the value is `Function`, the first parameter is the default configuration v Currently provided is as follows: -| Tools | Config | -| ----------------- | ---------------------------------------------------------------- | -| DevServer | [tools.devServer](/configure/app/tools/dev-server) | -| Babel | [tools.babel](/configure/app/tools/babel) | -| styled-components | [tools.styledComponents](/configure/app/tools/styled-components) | -| PostCSS | [tools.postcss](/configure/app/tools/postcss) | -| Less | [tools.less](/configure/app/tools/less) | -| Sass | [tools.sass](/configure/app/tools/sass) | -| Minify CSS | [tools.minifyCss](/configure/app/tools/minify-css) | -| Autoprefixer | [tools.autoprefixer](/configure/app/tools/autoprefixer) | +| Tools | Config | +| ------------ | ------------------------------------------------------- | +| DevServer | [tools.devServer](/configure/app/tools/dev-server) | +| Babel | [tools.babel](/configure/app/tools/babel) | +| PostCSS | [tools.postcss](/configure/app/tools/postcss) | +| Less | [tools.less](/configure/app/tools/less) | +| Sass | [tools.sass](/configure/app/tools/sass) | +| Minify CSS | [tools.minifyCss](/configure/app/tools/minify-css) | +| Autoprefixer | [tools.autoprefixer](/configure/app/tools/autoprefixer) | diff --git a/packages/document/docs/en/guides/basic-features/css/css-in-js.mdx b/packages/document/docs/en/guides/basic-features/css/css-in-js.mdx index 2613a4b34021..ec94fcf48b18 100644 --- a/packages/document/docs/en/guides/basic-features/css/css-in-js.mdx +++ b/packages/document/docs/en/guides/basic-features/css/css-in-js.mdx @@ -1,31 +1,34 @@ # Using CSS-in-JS -CSS-in-JS is a technique that allows you to write CSS styles in JS files. +CSS-in-JS is a technique that allows you to write CSS styles within JS files. -Modern.js supports the popular CSS-in-JS implementation library [styled-components](https://styled-components.com/), which uses the new JavaScript feature [Tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) to write component CSS styles. You can directly import the API of [styled-components](https://styled-components.com/) from `@modern-js/runtime/styled` for use. +Modern.js supports the commonly used community CSS-in-JS library [styled-components](https://styled-components.com/), which uses JavaScript's new feature [Tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) 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` dependency: -```bash -# npm -npm add @rsbuild/plugin-styled-components -D +First, you need to install the `styled-components` plugin dependency: -# yarn -yarn add @rsbuild/plugin-styled-components -D +import { PackageManagerTabs } from '@theme'; -# pnpm -pnpm add @rsbuild/plugin-styled-components -D -``` -Then, configure the `styled-components` plugin in `modern.config.ts`: + + +Then configure the `styled-components` plugin in `modern.config.ts`: ```ts import { defineConfig } from '@modern-js/app-tools'; -import { pluginStyledComponents } from '@rsbuild/plugin-styled-components'; +import { styledComponentsPlugin } from '@modern-js/plugin-styled-components'; export default defineConfig({ - builderPlugins: [ - pluginStyledComponents({ + plugins: [ + styledComponentsPlugin({ // ... displayName: true, minify: process.env.NODE_ENV === 'production', @@ -34,22 +37,24 @@ export default defineConfig({ }); ``` -## Writing Styles with styled-components +The configuration options of the styledComponentsPlugin plugin are the same as those of the [@rsbuild/plugin-styled-components](https://www.npmjs.com/package/@rsbuild/plugin-styled-components) plugin. You can refer to the documentation of [@rsbuild/plugin-styled-components](https://www.npmjs.com/package/@rsbuild/plugin-styled-components) for configuration. -When you need to write a `div` component with an internal font color of red, you can implement it as follows: +## Writing styles with styled-components + +When you need to write a `div` component with red text inside, you can implement it as follows: ```js -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/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: +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: ```js -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; const Button = styled.button` color: ${props => (props.primary ? 'white' : 'red')}; @@ -57,10 +62,8 @@ const Button = styled.button` `; ``` -For more usage of styled-components, please refer to [styled-components official website](https://styled-components.com/). - -Modern.js integrates Babel's [babel-plugin-styled-components](https://github.com/styled-components/babel-plugin-styled-components) plugin internally, and you can configure the plugin through [tools.styledComponents](/configure/app/tools/styled-components). +For more usage of styled-components, please refer to the [styled-components official website](https://styled-components.com/). -:::tip -If you need to use other CSS-in-JS libraries such as [styled-jsx](https://www.npmjs.com/package/styled-jsx) and [Emotion](https://emotion.sh/), you need to install the corresponding dependencies first. For specific usage, please refer to the library's official website. +:::tip Tip +If you want to use other CSS-in-JS libraries such as [styled-jsx](https://www.npmjs.com/package/styled-jsx), [Emotion](https://emotion.sh/), etc., you need to install the corresponding dependencies first. Please refer to the official websites of the respective libraries for specific usage. ::: diff --git a/packages/document/docs/en/guides/troubleshooting/builder.mdx b/packages/document/docs/en/guides/troubleshooting/builder.mdx index 40a53a693173..96f85f6ef977 100644 --- a/packages/document/docs/en/guides/troubleshooting/builder.mdx +++ b/packages/document/docs/en/guides/troubleshooting/builder.mdx @@ -188,20 +188,6 @@ export default { }; ``` -In addition to the reasons mentioned above, there is another possibility that can cause Babel compilation to hang, which is when Babel compiles a large JS file exceeding 10,000 lines (usually a large file in the node_modules directory that is compiled using `source.include`). - -When Babel compiles large files, the built-in babel-plugin-styled-components in Modern.js can cause the compilation to hang. There is already a [relevant issue](https://github.com/styled-components/babel-plugin-styled-components/issues/374) in the community . - -In the future, Modern.js will consider removing the built-in babel-plugin-styled-components. In the current version, you can set [tools.styledComponents](/configure/app/tools/styled-components.html) to `false` to remove this plugin. - -```ts title="modern.config.ts" -export default { - tools: { - styledComponents: false, - }, -}; -``` - --- ### The webpack cache does not work? diff --git a/packages/document/docs/en/plugin/introduction.mdx b/packages/document/docs/en/plugin/introduction.mdx index 36d4ae50af2d..ef10a055a190 100644 --- a/packages/document/docs/en/plugin/introduction.mdx +++ b/packages/document/docs/en/plugin/introduction.mdx @@ -138,18 +138,16 @@ You can read [Rsbuild Official Website - Plugins](https://rsbuild.rs/plugins/lis The following are official Rsbuild plugins that are already built into Modern.js. They can be enabled without installation: -| Plugin | Description | Modern.js Link | -| ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| [React Plugin](https://rsbuild.rs/zh/plugins/list/plugin-react) | Provides support for React | - | -| [SVGR Plugin](https://rsbuild.rs/zh/plugins/list/plugin-svgr) | Supports converting SVG images into React components | [output.disableSvgr](/configure/app/output/disable-svgr)
[output.svgDefaultExport](/configure/app/output/svg-default-export) | -| [Styled Components Plugin](https://github.com/rspack-contrib/rsbuild-plugin-styled-components) | Provides compile-time support for styled-components | [tools.styledComponents](/configure/app/tools/styled-components.html) | -| [Assets Retry Plugin](https://rsbuild.rs/zh/plugins/list/plugin-assets-retry) | Automatically retries requests when static asset loading fails | [output.assetsRetry](/configure/app/output/assets-retry.html) | -| [Type Check Plugin](https://github.com/rspack-contrib/rsbuild-plugin-type-check) | Runs TypeScript type checking in a separate process | [output.disableTsChecker](/configure/app/output/disable-ts-checker.html)
[tools.tsChecker](/configure/app/tools/ts-checker.html) | -| [Source Build Plugin](https://github.com/rspack-contrib/rsbuild-plugin-source-build) | For monorepo scenarios, supports referencing source code from other subdirectories and completing builds and hot updates | [experiments.sourceBuild](/configure/app/experiments/source-build.html) | -| [Check Syntax Plugin](https://github.com/rspack-contrib/rsbuild-plugin-check-syntax) | Analyzes the syntax compatibility of the build artifacts to determine if there are any advanced syntax features that cause compatibility issues | [security.checkSyntax](/configure/app/security/check-syntax.html) | -| [CSS Minimizer Plugin](https://github.com/rspack-contrib/rsbuild-plugin-css-minimizer) | Used to customize the CSS compression tool, switch to [cssnano](https://cssnano.co/) or other tools for CSS compression | [tools.minifyCss](/configure/app/tools/minify-css.html) | -| [Rem Plugin](https://github.com/rspack-contrib/rsbuild-plugin-rem) | Implements rem adaptive layout for mobile pages | [output.convertToRem](/configure/app/output/convert-to-rem.html) | - +| Plugin | Description | Modern.js Link | +| -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| [React Plugin](https://rsbuild.rs/zh/plugins/list/plugin-react) | Provides support for React | - | +| [SVGR Plugin](https://rsbuild.rs/zh/plugins/list/plugin-svgr) | Supports converting SVG images into React components | [output.disableSvgr](/configure/app/output/disable-svgr)
[output.svgDefaultExport](/configure/app/output/svg-default-export) | +| [Assets Retry Plugin](https://rsbuild.rs/zh/plugins/list/plugin-assets-retry) | Automatically retries requests when static asset loading fails | [output.assetsRetry](/configure/app/output/assets-retry.html) | +| [Type Check Plugin](https://github.com/rspack-contrib/rsbuild-plugin-type-check) | Runs TypeScript type checking in a separate process | [output.disableTsChecker](/configure/app/output/disable-ts-checker.html)
[tools.tsChecker](/configure/app/tools/ts-checker.html) | +| [Source Build Plugin](https://github.com/rspack-contrib/rsbuild-plugin-source-build) | For monorepo scenarios, supports referencing source code from other subdirectories and completing builds and hot updates | [experiments.sourceBuild](/configure/app/experiments/source-build.html) | +| [Check Syntax Plugin](https://github.com/rspack-contrib/rsbuild-plugin-check-syntax) | Analyzes the syntax compatibility of the build artifacts to determine if there are any advanced syntax features that cause compatibility issues | [security.checkSyntax](/configure/app/security/check-syntax.html) | +| [CSS Minimizer Plugin](https://github.com/rspack-contrib/rsbuild-plugin-css-minimizer) | Used to customize the CSS compression tool, switch to [cssnano](https://cssnano.co/) or other tools for CSS compression | [tools.minifyCss](/configure/app/tools/minify-css.html) | +| [Rem Plugin](https://github.com/rspack-contrib/rsbuild-plugin-rem) | Implements rem adaptive layout for mobile pages | [output.convertToRem](/configure/app/output/convert-to-rem.html) | #### Plugins Not Built-in @@ -161,7 +159,6 @@ The following are official Rsbuild plugins that are not built into Modern.js: - [YAML Plugin](https://github.com/rspack-contrib/rsbuild-plugin-yaml): Used to reference YAML files and convert them to JavaScript objects. - [TOML Plugin](https://github.com/rspack-contrib/rsbuild-plugin-toml): Used to reference TOML files and convert them to JavaScript objects. - import OtherPlugins from '@site-docs-en/components/other-plugins.mdx'; diff --git a/packages/document/docs/en/plugin/official/cli-plugins/_meta.json b/packages/document/docs/en/plugin/official/cli-plugins/_meta.json index 575b56365ecb..635cc8101a8f 100644 --- a/packages/document/docs/en/plugin/official/cli-plugins/_meta.json +++ b/packages/document/docs/en/plugin/official/cli-plugins/_meta.json @@ -1 +1 @@ -["plugin-bff", "plugin-ssg"] +["plugin-bff", "plugin-ssg", "plugin-styled-components"] diff --git a/packages/document/docs/en/plugin/official/cli-plugins/plugin-styled-components.mdx b/packages/document/docs/en/plugin/official/cli-plugins/plugin-styled-components.mdx new file mode 100644 index 000000000000..a145ca09d32d --- /dev/null +++ b/packages/document/docs/en/plugin/official/cli-plugins/plugin-styled-components.mdx @@ -0,0 +1,5 @@ +# styled-components Plugin + +In a Modern.js application, developers can use the styled-components plugin to utilize the styled-components library within the app, enabling CSS-in-JS functionality. + +For more details, please refer to [Using CSS-in-JS](/guides/basic-features/css/css-in-js). diff --git a/packages/document/docs/zh/apis/app/runtime/utility/css-in-js.mdx b/packages/document/docs/zh/apis/app/runtime/utility/css-in-js.mdx index f0d70deb9e34..380aa66111ac 100644 --- a/packages/document/docs/zh/apis/app/runtime/utility/css-in-js.mdx +++ b/packages/document/docs/zh/apis/app/runtime/utility/css-in-js.mdx @@ -1,6 +1,7 @@ --- title: CSS-In-JS API --- + # CSS-In-JS API 使用 Style Component 来编写组件 CSS。 @@ -8,7 +9,7 @@ title: CSS-In-JS API ## 使用姿势 ```ts -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; ``` ## 函数签名 @@ -18,7 +19,7 @@ import styled from '@modern-js/runtime/styled'; ## 示例 ```tsx -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; const Button = styled.button` background: palevioletred; diff --git a/packages/document/docs/zh/configure/app/tools/ts-loader.mdx b/packages/document/docs/zh/configure/app/tools/ts-loader.mdx index b12347ccfa82..6e395e953265 100644 --- a/packages/document/docs/zh/configure/app/tools/ts-loader.mdx +++ b/packages/document/docs/zh/configure/app/tools/ts-loader.mdx @@ -6,7 +6,7 @@ title: tsLoader import { Badge } from '@theme'; -仅支持 Webpack +仅支持 Webpack - **类型:** `Object | Function | undefined` - **默认值:** `undefined` @@ -15,7 +15,7 @@ import { Badge } from '@theme'; 不推荐在项目中使用 ts-loader,原因如下: -- 启用 ts-loader 时将无法使用 [source.transformImport](/configure/app/source/transform-import) 和 [tools.styledComponents](/configure/app/tools/styled-components) 等由 Babel 和 SWC 提供支持的能力。 +- 启用 ts-loader 时将无法使用 [source.transformImport](/configure/app/source/transform-import) 等由 Babel 和 SWC 提供支持的能力。 - Rspack 不支持使用 ts-loader。 ::: diff --git a/packages/document/docs/zh/guides/advanced-features/low-level.mdx b/packages/document/docs/zh/guides/advanced-features/low-level.mdx index 5667c811a07a..6a41d53b2677 100644 --- a/packages/document/docs/zh/guides/advanced-features/low-level.mdx +++ b/packages/document/docs/zh/guides/advanced-features/low-level.mdx @@ -28,13 +28,12 @@ export default defineConfig({ 目前提供的底层配置如下表: -| 底层工具 | 配置 | -| ----------------- | ---------------------------------------------------------------- | -| DevServer | [tools.devServer](/configure/app/tools/dev-server) | -| Babel | [tools.babel](/configure/app/tools/babel) | -| styled-components | [tools.styledComponents](/configure/app/tools/styled-components) | -| PostCSS | [tools.postcss](/configure/app/tools/postcss) | -| Less | [tools.less](/configure/app/tools/less) | -| Sass | [tools.sass](/configure/app/tools/sass) | -| Minify CSS | [tools.minifyCss](/configure/app/tools/minify-css) | -| Autoprefixer | [tools.autoprefixer](/configure/app/tools/autoprefixer) | +| 底层工具 | 配置 | +| ------------ | ------------------------------------------------------- | +| DevServer | [tools.devServer](/configure/app/tools/dev-server) | +| Babel | [tools.babel](/configure/app/tools/babel) | +| PostCSS | [tools.postcss](/configure/app/tools/postcss) | +| Less | [tools.less](/configure/app/tools/less) | +| Sass | [tools.sass](/configure/app/tools/sass) | +| Minify CSS | [tools.minifyCss](/configure/app/tools/minify-css) | +| Autoprefixer | [tools.autoprefixer](/configure/app/tools/autoprefixer) | diff --git a/packages/document/docs/zh/guides/basic-features/css/css-in-js.mdx b/packages/document/docs/zh/guides/basic-features/css/css-in-js.mdx index 5b8fdd46d185..7e3a83e42509 100644 --- a/packages/document/docs/zh/guides/basic-features/css/css-in-js.mdx +++ b/packages/document/docs/zh/guides/basic-features/css/css-in-js.mdx @@ -2,31 +2,33 @@ CSS-in-JS 是一种可以将 CSS 样式写在 JS 文件里的技术。 -Modern.js 支持社区常用的 CSS-in-JS 实现库 [styled-components](https://styled-components.com/),它使用 JavaScript 的新特性 [Tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) 编写组件的 CSS 样式。可以直接从 `@modern-js/runtime/styled` 引入 [styled-components](https://styled-components.com/) 的 API 进行使用。 +Modern.js 支持社区常用的 CSS-in-JS 实现库 [styled-components](https://styled-components.com/),它使用 JavaScript 的新特性 [Tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) 编写组件的 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` 插件依赖: -```bash -# npm -npm add @rsbuild/plugin-styled-components -D +import { PackageManagerTabs } from '@theme'; -# yarn -yarn add @rsbuild/plugin-styled-components -D + -# pnpm -pnpm add @rsbuild/plugin-styled-components -D -``` 然后在 `modern.config.ts` 中配置 `styled-components` 插件: ```ts import { defineConfig } from '@modern-js/app-tools'; -import { pluginStyledComponents } from '@rsbuild/plugin-styled-components'; +import { styledComponentsPlugin } from '@modern-js/plugin-styled-components'; export default defineConfig({ - builderPlugins: [ - pluginStyledComponents({ + plugins: [ + styledComponentsPlugin({ // ... displayName: true, minify: process.env.NODE_ENV === 'production', @@ -35,12 +37,14 @@ export default defineConfig({ }); ``` +styledComponentsPlugin 插件的配置项与 [@rsbuild/plugin-styled-components](https://www.npmjs.com/package/@rsbuild/plugin-styled-components) 插件的配置项相同,你可以参考 [@rsbuild/plugin-styled-components](https://www.npmjs.com/package/@rsbuild/plugin-styled-components) 插件的文档进行配置。 + ## 使用 styled-components 编写样式 当需要编写一个内部字体为红色的 `div` 组件时,可以如下实现: ```js -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; const RedDiv = styled.div` color: red; @@ -50,7 +54,7 @@ const RedDiv = styled.div` 当需要根据组件的 `props` 动态设置组件样式时,例如 `props` 的属性 `primary` 为 `true` 时,按钮的颜色为白色,其他情况为红色,实现代码如下: ```js -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; const Button = styled.button` color: ${props => (props.primary ? 'white' : 'red')}; @@ -60,8 +64,6 @@ const Button = styled.button` 关于 styled-components 的更多用法,请参考 [styled-components 官网](https://styled-components.com/)。 -Modern.js 内部集成了 Babel 的 [babel-plugin-styled-components](https://github.com/styled-components/babel-plugin-styled-components) 插件,你可以通过 [tools.styledComponents](/configure/app/tools/styled-components) 对插件进行配置。 - :::tip 提示 如果需要使用 [styled-jsx](https://www.npmjs.com/package/styled-jsx)、[Emotion](https://emotion.sh/) 等其他 CSS-in-JS 库,需要先安装对应库的依赖。具体使用方式请参考对应库的官网。 ::: diff --git a/packages/document/docs/zh/guides/troubleshooting/builder.mdx b/packages/document/docs/zh/guides/troubleshooting/builder.mdx index 6e1800d2f06e..b2f6b886cf65 100644 --- a/packages/document/docs/zh/guides/troubleshooting/builder.mdx +++ b/packages/document/docs/zh/guides/troubleshooting/builder.mdx @@ -188,20 +188,6 @@ export default { }; ``` -除了上述原因外,还有一种可能会导致 Babel 编译卡死,就是使用 Babel 编译了一个超过 1 万行的大型 JS 文件(通常是使用 `source.include` 编译了 node_modules 中的某个大文件)。 - -当 Babel 编译大文件时,Modern.js 内置的 babel-plugin-styled-components 会卡死,社区中已有 [相关 issue](https://github.com/styled-components/babel-plugin-styled-components/issues/374)。 - -未来 Modern.js 会考虑移除内置的 babel-plugin-styled-components。在当前版本里,你可以将 [tools.styledComponents](/configure/app/tools/styled-components.html) 设置为 `false` 来移除该插件。 - -```ts title="modern.config.ts" -export default { - tools: { - styledComponents: false, - }, -}; -``` - --- ### webpack 编译缓存未生效,应该如何排查? diff --git a/packages/document/docs/zh/plugin/introduction.mdx b/packages/document/docs/zh/plugin/introduction.mdx index 7560a0684f5e..436938aad91c 100644 --- a/packages/document/docs/zh/plugin/introduction.mdx +++ b/packages/document/docs/zh/plugin/introduction.mdx @@ -138,17 +138,16 @@ Modern.js 从 `MAJOR_VERSION.46.0` 起,底层构建工具升级为 [Rsbuild](h 以下为已在 Modern.js 中内置的 Rsbuild 官方插件,无需安装,即可启用: -| 插件 | 介绍 | Modern.js 链接 | -| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| [React 插件](https://rsbuild.rs/zh/plugins/list/plugin-react) | 提供对 React 的支持 | - | -| [SVGR 插件](https://rsbuild.rs/zh/plugins/list/plugin-svgr) | 支持将 SVG 图片转换为一个 React 组件 | [output.disableSvgr](/configure/app/output/disable-svgr)
[output.svgDefaultExport](/configure/app/output/svg-default-export) | -| [Styled Components 插件](https://github.com/rspack-contrib/rsbuild-plugin-styled-components) | 提供对 styled-components 的编译时支持 | [tools.styledComponents](/configure/app/tools/styled-components.html) | -| [Assets Retry 插件](https://rsbuild.rs/zh/plugins/list/plugin-assets-retry) | 用于在静态资源加载失败时自动发起重试请求 | [output.assetsRetry](/configure/app/output/assets-retry.html) | -| [Type Check 插件](https://github.com/rspack-contrib/rsbuild-plugin-type-check) | 用于在单独的进程中运行 TypeScript 类型检查 | [output.disableTsChecker](/configure/app/output/disable-ts-checker.html)
[tools.tsChecker](/configure/app/tools/ts-checker.html) | -| [Source Build 插件](https://github.com/rspack-contrib/rsbuild-plugin-source-build) | 用于 monorepo 场景,支持引用其他子目录的源代码,并完成构建和热更新 | [experiments.sourceBuild](/configure/app/experiments/source-build.html) | -| [Check Syntax 插件](https://github.com/rspack-contrib/rsbuild-plugin-check-syntax) | 用于分析产物的语法兼容性,判断是否存在导致兼容性问题的高级语法 | [security.checkSyntax](/configure/app/security/check-syntax.html) | -| [CSS Minimizer 插件](https://github.com/rspack-contrib/rsbuild-plugin-css-minimizer) | 用于自定义 CSS 压缩工具,切换到 [cssnano](https://cssnano.co/) 或其他工具进行 CSS 压缩 | [tools.minifyCss](/configure/app/tools/minify-css.html) | -| [Rem 插件](https://github.com/rspack-contrib/rsbuild-plugin-rem) | 用于实现移动端页面的 rem 自适应布局 | [output.convertToRem](/configure/app/output/convert-to-rem.html) | +| 插件 | 介绍 | Modern.js 链接 | +| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| [React 插件](https://rsbuild.rs/zh/plugins/list/plugin-react) | 提供对 React 的支持 | - | +| [SVGR 插件](https://rsbuild.rs/zh/plugins/list/plugin-svgr) | 支持将 SVG 图片转换为一个 React 组件 | [output.disableSvgr](/configure/app/output/disable-svgr)
[output.svgDefaultExport](/configure/app/output/svg-default-export) | +| [Assets Retry 插件](https://rsbuild.rs/zh/plugins/list/plugin-assets-retry) | 用于在静态资源加载失败时自动发起重试请求 | [output.assetsRetry](/configure/app/output/assets-retry.html) | +| [Type Check 插件](https://github.com/rspack-contrib/rsbuild-plugin-type-check) | 用于在单独的进程中运行 TypeScript 类型检查 | [output.disableTsChecker](/configure/app/output/disable-ts-checker.html)
[tools.tsChecker](/configure/app/tools/ts-checker.html) | +| [Source Build 插件](https://github.com/rspack-contrib/rsbuild-plugin-source-build) | 用于 monorepo 场景,支持引用其他子目录的源代码,并完成构建和热更新 | [experiments.sourceBuild](/configure/app/experiments/source-build.html) | +| [Check Syntax 插件](https://github.com/rspack-contrib/rsbuild-plugin-check-syntax) | 用于分析产物的语法兼容性,判断是否存在导致兼容性问题的高级语法 | [security.checkSyntax](/configure/app/security/check-syntax.html) | +| [CSS Minimizer 插件](https://github.com/rspack-contrib/rsbuild-plugin-css-minimizer) | 用于自定义 CSS 压缩工具,切换到 [cssnano](https://cssnano.co/) 或其他工具进行 CSS 压缩 | [tools.minifyCss](/configure/app/tools/minify-css.html) | +| [Rem 插件](https://github.com/rspack-contrib/rsbuild-plugin-rem) | 用于实现移动端页面的 rem 自适应布局 | [output.convertToRem](/configure/app/output/convert-to-rem.html) | #### 未内置的插件 diff --git a/packages/document/docs/zh/plugin/official/cli-plugins/_meta.json b/packages/document/docs/zh/plugin/official/cli-plugins/_meta.json index 575b56365ecb..635cc8101a8f 100644 --- a/packages/document/docs/zh/plugin/official/cli-plugins/_meta.json +++ b/packages/document/docs/zh/plugin/official/cli-plugins/_meta.json @@ -1 +1 @@ -["plugin-bff", "plugin-ssg"] +["plugin-bff", "plugin-ssg", "plugin-styled-components"] diff --git a/packages/document/docs/zh/plugin/official/cli-plugins/plugin-styled-components.mdx b/packages/document/docs/zh/plugin/official/cli-plugins/plugin-styled-components.mdx new file mode 100644 index 000000000000..fd38fcfa89a0 --- /dev/null +++ b/packages/document/docs/zh/plugin/official/cli-plugins/plugin-styled-components.mdx @@ -0,0 +1,5 @@ +# styled-components 插件 + +在 Modern.js 应用中,通过 styled-components 插件,开发者可以在应用中使用 styled-components 库,实现 CSS-in-JS 的功能。 + +详细内容可以参考 [使用 CSS-in-JS](/guides/basic-features/css/css-in-js)。 diff --git a/packages/document/docs/zh/tutorials/first-app/c03-css.mdx b/packages/document/docs/zh/tutorials/first-app/c03-css.mdx index f6ff6c35d635..e90ae7c6e846 100644 --- a/packages/document/docs/zh/tutorials/first-app/c03-css.mdx +++ b/packages/document/docs/zh/tutorials/first-app/c03-css.mdx @@ -23,7 +23,7 @@ styled-components 通过模块化的方式,避免了传统 CSS 写法上的诸 在 `src/routes/page.tsx` 里修改顶部的代码: ```js -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; ``` 添加以下代码: @@ -81,7 +81,7 @@ import Avatar from '../components/Avatar'; `src/components/Avatar/index.tsx` 的内容,修改为: ```ts -import styled from '@modern-js/runtime/styled'; +import styled from '@modern-js/plugin-styled-components/styled'; const Avatar = styled.img` width: 50px; diff --git a/packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx b/packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx new file mode 100644 index 000000000000..f7670bf206aa --- /dev/null +++ b/packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx @@ -0,0 +1,334 @@ +--- +title: Add Style +--- + +# Add Style + +import { Tabs, Tab as TabItem } from '@theme'; + +In the previous chapter, we learned how to use components from the third-party library. + +In this chapter, we will learn how to implement UI components. + +## JS components using CSS + +First of all, we want to control the display of contact avatars by ourselves, and implement this design draft: + +![design](https://lf3-static.bytednsdoc.com/obj/eden-cn/nuvjhpqnuvr/modern-website/tutorials/c03-css-expect.jpg) + +Hypothesis has no ready-made components to implement, so you need to write some CSS yourself. Here we use [styled-components](https://styled-components.com/) to implement similar requirements. Modern.js out of the box supports styled-components, which requires neither dependency nor configuration. + +Style-components avoids many problems of traditional CSS writing through modularization. For example, writing styles directly on the style attribute of elements, the visual details of UI will also be mixed with the details of UI structure and business logic. Or classname needs to avoid global space renaming, which requires the use of naming conventions. + +Modify the code at the top in `src/routes/page.tsx`: + +```js +import styled from '@modern-js/plugin-styled-components/styled'; +``` + +Add the following code: + +```js +const Avatar = styled.img` + width: 50px; + height: 50px; + border: 4px solid #0ef; + border-radius: 50%; +`; +``` + +Modify the code of `List.Item.Meta`: + +```tsx +} + title={name} + description={email} +/> +``` + +Execute `pnpm run dev` to see the expected running result: + +![result](https://lf3-static.bytednsdoc.com/obj/eden-cn/nuvjhpqnuvr/modern-website/tutorials/c03-css-result1.png) + +Next we do a little refactoring. To enhance legibility and make the code easier to maintain, we can split the Avatar component. We execute the following command at the end point to create a new file: + + + + +```bash +mkdir -p src/components/Avatar +touch src/components/Avatar/index.tsx +``` + + + + +```powershell +mkdir -p src/components/Avatar +ni src/components/Avatar/index.tsx +``` + + + + +Delete the `` implementation in `src/routes/page.tsx` and change it to: + +```ts +import Avatar from '../components/Avatar'; +``` + +The content of `src/components/Avatar/index.tsx` is modified to: + +```ts +import styled from '@modern-js/plugin-styled-components/styled'; + +const Avatar = styled.img` + width: 50px; + height: 50px; + border: 4px solid #0ef; + border-radius: 50%; +`; + +export default Avatar; +``` + +Execute `pnpm run dev`, the result should be the same. + +:::info note +The reason for using the directory form `Avatar/index.tsx` instead of the single-file form `Avatar.tsx` is that you can easily add sub-files inside the directory later, including dedicated resources (pictures, etc.), dedicated sub-components, CSS files, etc. + +::: + +## Utility + +We have used the style-components implementation `` component, but the current UI is still unsatisfactory and lacks professionalism, such as the list item inhouse layout is a bit rough and misaligned in many places. + +Now, let's implement a better `Item` component ourselves, implementing a design draft like this: + +![design](https://lf3-static.bytednsdoc.com/obj/eden-cn/aphqeh7uhohpquloj/modern-js/docs/06/design2.png) + +The UI to be implemented this time is more complex and has an internal structure, but on the other hand, there is no very thick bright blue border of the `` component such a very special UI, which is a very conventional horizontal and vertical layout, centering, font style, etc. In this case, there is actually no need to write CSS at all. There is a more efficient implementation method that complements styled-components: **Utility Class**. + +Modern.js integrates the mainstream, light, general-purpose Utility Class library [Tailwind CSS](https://tailwindcss.com/). + +Install the tailwindcss package to integrate Tailwind CSS: + +import { PackageManagerTabs } from '@theme'; + + + +Register the tailwindcss PostCSS plugin via `postcss.config.cjs`: + +```js title="postcss.config.cjs" +module.exports = { + plugins: { + tailwindcss: {}, + }, +}; +``` + +Create a tailwind.config.js file in the root directory of the current project and add the following content: + +```js title="tailwind.config.js" +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: ['./src/**/*.{html,js,ts,jsx,tsx}'], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the @tailwind directives in the CSS entry file: + +```css title="main.css" +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Create the Item component first: + + + + +```bash +mkdir -p src/components/Item +touch src/components/Item/index.tsx +``` + + + + +```powershell +mkdir -p src/components/Item +ni src/components/Item/index.tsx +``` + + + + +Modify `src/routes/page.tsx` to pass the `render` implementation of `List` to `Item` component: + +```js +import { List } from 'antd'; +import 'tailwindcss/base.css'; +import 'tailwindcss/components.css'; +import 'tailwindcss/utilities.css'; +import Item from '../components/Item'; + +const getAvatar = (users: Array<{ name: string, email: string }>) => + users.map(user => ({ + ...user, + avatar: `https://api.dicebear.com/7.x/pixel-art/svg?seed=${user.name}`, + })); + +const mockData = getAvatar([ + { name: 'Thomas', email: 'w.kccip@bllmfbgv.dm' }, + { name: 'Chow', email: 'f.lfqljnlk@ywoefljhc.af' }, + { name: 'Bradley', email: 'd.wfovsqyo@gpkcjwjgb.fr' }, + { name: 'Davis', email: '"t.kqkoj@utlkwnpwk.nu' }, +]); + +function Index() { + return ( +
+ } + /> +
+ ); +} + +export default Index; +``` + +Utility Class(https://tailwindcss.com/docs/container) is used on the parent container for a quick implementation of the most basic maximum width, center, and other styles. + +Next implementation `src/components/Item/index.tsx`: + +```tsx +import Avatar from '../Avatar'; + +type InfoProps = { + avatar: string; + name: string; + email: string; + archived?: boolean; +}; + +const Item = ({ info }: { info: InfoProps }) => { + const { avatar, name, email, archived } = info; + return ( +
+ +
+
+

{name}

+

{email}

+
+ +
+
+ ); +}; + +export default Item; +``` + +Execute `pnpm run dev` to see the expected running result: + +![result](https://lf3-static.bytednsdoc.com/obj/eden-cn/aphqeh7uhohpquloj/modern-js/docs/06/result2.png) + +We only use a few Utility Classes, such as [Flex](https://tailwindcss.com/docs/display/), [Padding](https://tailwindcss.com/docs/padding/), [Margin](https://tailwindcss.com/docs/margin/), [Text](https://tailwindcss.com/docs/text-color/), [Font](https://tailwindcss.com/docs/font-weight/), [Border](https://tailwindcss.com/docs/border-width), without writing a single CSS implementation Professional UI that conforms to the design draft. + +## Customized Utility Class + +We can also implement the new Utility Class ourselves to facilitate reuse between codes. + +Utility Class itself is also a **component-oriented** technology (using different classes on a component is equivalent to setting some attributes from the base class for this component), but the classname of Utility Class is global (because it is used on arbitrary components/elements), it is very suitable for implementation with separate CSS files. + +Create a new CSS file: + + + + +```bash +mkdir -p src/styles +touch src/styles/utils.css +``` + + + + +```powershell +mkdir -p src/styles +ni src/styles/utils.css +``` + + + + +Import `utils.css` in `src/routes/page.tsx`: + +```js +import '../styles/utils.css'; +``` + +A Utility Class named `custom-text-gray` is implemented in `src/routes/styles/utils.css`. + +```css +:root { + --custom-text-color: rgb(113, 128, 150); +} + +.custom-text-gray { + color: var(--custom-text-color); +} +``` + +:::info note +Modern.js integrates with [PostCSS](/guides/basic-features/css/css) and supports modern CSS syntax features such as [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties). + +::: + +Use in `src/components/Item/index.tsx`: + +```js +
+``` + +Change to: + +```js +
+``` + +Execute `pnpm run dev`, you can see that the font color has changed: + +![design2](https://lf3-static.bytednsdoc.com/obj/eden-cn/aphqeh7uhohpquloj/modern-js/docs/06/result3.png) + +:::info note +This is just to demonstrate Utility Class usage. In a real project, with Tailwind CSS, this Utility Class is of little value and should be added to the font color through the [**theme**](https://tailwindcss.com/docs/customizing-colors) of the configuration Design System. + +`utils.css` can also be written as `utils.scss` or `utils.less`, Modern.js out of the box support for SCSS and Less. + +However, with the support of PostCSS, modern CSS should be sufficient to meet these development needs, and the performance is also better than that of the preprocessor. It is recommended to use `.css` files first. + +::: diff --git a/tests/integration/styled-components/fixtures/stream/modern.config.ts b/tests/integration/styled-components/fixtures/stream/modern.config.ts index 0fa44227f6af..a0fbfaccae5d 100644 --- a/tests/integration/styled-components/fixtures/stream/modern.config.ts +++ b/tests/integration/styled-components/fixtures/stream/modern.config.ts @@ -10,5 +10,10 @@ export default applyBaseConfig({ mode: 'stream', }, }, - plugins: [styledComponentsPlugin()], + plugins: [ + styledComponentsPlugin({ + minify: process.env.NODE_ENV === 'production', + namespace: 'my-styled-components', + }), + ], }); From b965dc52955f2690b3717a7437334d56819bf587 Mon Sep 17 00:00:00 2001 From: zhangxiang Date: Tue, 18 Nov 2025 18:47:40 +0800 Subject: [PATCH 2/2] feat: rebase main --- .../configure/app/tools/styled-components.mdx | 55 --- .../configure/app/tools/styled-components.mdx | 54 --- .../docs/en/tutorials/first-app/c03-css.mdx | 334 ------------------ 3 files changed, 443 deletions(-) delete mode 100644 packages/document/docs/en/configure/app/tools/styled-components.mdx delete mode 100644 packages/document/docs/zh/configure/app/tools/styled-components.mdx delete mode 100644 packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx diff --git a/packages/document/docs/en/configure/app/tools/styled-components.mdx b/packages/document/docs/en/configure/app/tools/styled-components.mdx deleted file mode 100644 index e84835348109..000000000000 --- a/packages/document/docs/en/configure/app/tools/styled-components.mdx +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: styledComponents ---- - -# tools.styledComponents - -- **Type:** `Object | Function` -- **Default:** - -```js -{ - displayName: true, - // `isSSR` is true in SSR build - ssr: isSSR, - // `pure` is enabled in production to reduce bundle size - pure: isProd, - transpileTemplateLiterals: true, -} -``` - -`tools.styledComponents` config is corresponding to [babel-plugin-styled-components](https://github.com/styled-components/babel-plugin-styled-components), or [@swc/plugin-styled-components](https://github.com/swc-project/plugins/tree/main/packages/styled-components) when using SWC plugin. - -When the value is an Object, use the Object.assign function to merge with the default config. For example: - -```js -export default { - tools: { - styledComponents: { - pure: false, - }, - }, -}; -``` - -When the config is a Function, the first parameter is the default configuration, and the second parameter provides some utility functions that can be called directly: - -```js -export default { - tools: { - styledComponents(config) { - config.pure = false; - }, - }, -}; -``` - -The feature is enabled by default, and you can configure `tools.styledComponents` to `false` to disable this behavior, which can improve build performance: - -```js -export default { - tools: { - styledComponents: false, - }, -}; -``` diff --git a/packages/document/docs/zh/configure/app/tools/styled-components.mdx b/packages/document/docs/zh/configure/app/tools/styled-components.mdx deleted file mode 100644 index f2ae953ef312..000000000000 --- a/packages/document/docs/zh/configure/app/tools/styled-components.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: styledComponents ---- - -# tools.styledComponents - -- **类型:** `Object | Function | false` -- **默认值:** - -```js -{ - displayName: true, - // 在 SSR 构建中 isSSR 为 true - ssr: isSSR, - // 在生产环境构建时启用 `pure` 来优化包体积 - pure: isProd, - transpileTemplateLiterals: true, -} -``` - -对应 [babel-plugin-styled-components](https://github.com/styled-components/babel-plugin-styled-components) 或使用 SWC 时 [@swc/plugin-styled-components](https://github.com/swc-project/plugins/tree/main/packages/styled-components) 的配置。 值为 `Object` 类型时,利用 Object.assign 函数与默认配置合并。比如: - -```js -export default { - tools: { - styledComponents: { - pure: false, - }, - }, -}; -``` - -值为 `Function` 类型时,第一个参数为默认配置,第二个参数提供了一些可以直接调用的工具函数: - -```js -export default { - tools: { - styledComponents(config) { - // 修改 pure 配置 - config.pure = false; - }, - }, -}; -``` - -该特性默认启用,你可以配置 `tools.styledComponents` 为 `false` 来关闭该行为,关闭后可以提升编译性能: - -```js -export default { - tools: { - styledComponents: false, - }, -}; -``` diff --git a/packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx b/packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx deleted file mode 100644 index f7670bf206aa..000000000000 --- a/packages/document/main-doc/docs/en/tutorials/first-app/c03-css.mdx +++ /dev/null @@ -1,334 +0,0 @@ ---- -title: Add Style ---- - -# Add Style - -import { Tabs, Tab as TabItem } from '@theme'; - -In the previous chapter, we learned how to use components from the third-party library. - -In this chapter, we will learn how to implement UI components. - -## JS components using CSS - -First of all, we want to control the display of contact avatars by ourselves, and implement this design draft: - -![design](https://lf3-static.bytednsdoc.com/obj/eden-cn/nuvjhpqnuvr/modern-website/tutorials/c03-css-expect.jpg) - -Hypothesis has no ready-made components to implement, so you need to write some CSS yourself. Here we use [styled-components](https://styled-components.com/) to implement similar requirements. Modern.js out of the box supports styled-components, which requires neither dependency nor configuration. - -Style-components avoids many problems of traditional CSS writing through modularization. For example, writing styles directly on the style attribute of elements, the visual details of UI will also be mixed with the details of UI structure and business logic. Or classname needs to avoid global space renaming, which requires the use of naming conventions. - -Modify the code at the top in `src/routes/page.tsx`: - -```js -import styled from '@modern-js/plugin-styled-components/styled'; -``` - -Add the following code: - -```js -const Avatar = styled.img` - width: 50px; - height: 50px; - border: 4px solid #0ef; - border-radius: 50%; -`; -``` - -Modify the code of `List.Item.Meta`: - -```tsx -} - title={name} - description={email} -/> -``` - -Execute `pnpm run dev` to see the expected running result: - -![result](https://lf3-static.bytednsdoc.com/obj/eden-cn/nuvjhpqnuvr/modern-website/tutorials/c03-css-result1.png) - -Next we do a little refactoring. To enhance legibility and make the code easier to maintain, we can split the Avatar component. We execute the following command at the end point to create a new file: - - - - -```bash -mkdir -p src/components/Avatar -touch src/components/Avatar/index.tsx -``` - - - - -```powershell -mkdir -p src/components/Avatar -ni src/components/Avatar/index.tsx -``` - - - - -Delete the `` implementation in `src/routes/page.tsx` and change it to: - -```ts -import Avatar from '../components/Avatar'; -``` - -The content of `src/components/Avatar/index.tsx` is modified to: - -```ts -import styled from '@modern-js/plugin-styled-components/styled'; - -const Avatar = styled.img` - width: 50px; - height: 50px; - border: 4px solid #0ef; - border-radius: 50%; -`; - -export default Avatar; -``` - -Execute `pnpm run dev`, the result should be the same. - -:::info note -The reason for using the directory form `Avatar/index.tsx` instead of the single-file form `Avatar.tsx` is that you can easily add sub-files inside the directory later, including dedicated resources (pictures, etc.), dedicated sub-components, CSS files, etc. - -::: - -## Utility - -We have used the style-components implementation `` component, but the current UI is still unsatisfactory and lacks professionalism, such as the list item inhouse layout is a bit rough and misaligned in many places. - -Now, let's implement a better `Item` component ourselves, implementing a design draft like this: - -![design](https://lf3-static.bytednsdoc.com/obj/eden-cn/aphqeh7uhohpquloj/modern-js/docs/06/design2.png) - -The UI to be implemented this time is more complex and has an internal structure, but on the other hand, there is no very thick bright blue border of the `` component such a very special UI, which is a very conventional horizontal and vertical layout, centering, font style, etc. In this case, there is actually no need to write CSS at all. There is a more efficient implementation method that complements styled-components: **Utility Class**. - -Modern.js integrates the mainstream, light, general-purpose Utility Class library [Tailwind CSS](https://tailwindcss.com/). - -Install the tailwindcss package to integrate Tailwind CSS: - -import { PackageManagerTabs } from '@theme'; - - - -Register the tailwindcss PostCSS plugin via `postcss.config.cjs`: - -```js title="postcss.config.cjs" -module.exports = { - plugins: { - tailwindcss: {}, - }, -}; -``` - -Create a tailwind.config.js file in the root directory of the current project and add the following content: - -```js title="tailwind.config.js" -/** @type {import('tailwindcss').Config} */ -module.exports = { - content: ['./src/**/*.{html,js,ts,jsx,tsx}'], - theme: { - extend: {}, - }, - plugins: [], -}; -``` - -Add the @tailwind directives in the CSS entry file: - -```css title="main.css" -@tailwind base; -@tailwind components; -@tailwind utilities; -``` - -Create the Item component first: - - - - -```bash -mkdir -p src/components/Item -touch src/components/Item/index.tsx -``` - - - - -```powershell -mkdir -p src/components/Item -ni src/components/Item/index.tsx -``` - - - - -Modify `src/routes/page.tsx` to pass the `render` implementation of `List` to `Item` component: - -```js -import { List } from 'antd'; -import 'tailwindcss/base.css'; -import 'tailwindcss/components.css'; -import 'tailwindcss/utilities.css'; -import Item from '../components/Item'; - -const getAvatar = (users: Array<{ name: string, email: string }>) => - users.map(user => ({ - ...user, - avatar: `https://api.dicebear.com/7.x/pixel-art/svg?seed=${user.name}`, - })); - -const mockData = getAvatar([ - { name: 'Thomas', email: 'w.kccip@bllmfbgv.dm' }, - { name: 'Chow', email: 'f.lfqljnlk@ywoefljhc.af' }, - { name: 'Bradley', email: 'd.wfovsqyo@gpkcjwjgb.fr' }, - { name: 'Davis', email: '"t.kqkoj@utlkwnpwk.nu' }, -]); - -function Index() { - return ( -
- } - /> -
- ); -} - -export default Index; -``` - -Utility Class(https://tailwindcss.com/docs/container) is used on the parent container for a quick implementation of the most basic maximum width, center, and other styles. - -Next implementation `src/components/Item/index.tsx`: - -```tsx -import Avatar from '../Avatar'; - -type InfoProps = { - avatar: string; - name: string; - email: string; - archived?: boolean; -}; - -const Item = ({ info }: { info: InfoProps }) => { - const { avatar, name, email, archived } = info; - return ( -
- -
-
-

{name}

-

{email}

-
- -
-
- ); -}; - -export default Item; -``` - -Execute `pnpm run dev` to see the expected running result: - -![result](https://lf3-static.bytednsdoc.com/obj/eden-cn/aphqeh7uhohpquloj/modern-js/docs/06/result2.png) - -We only use a few Utility Classes, such as [Flex](https://tailwindcss.com/docs/display/), [Padding](https://tailwindcss.com/docs/padding/), [Margin](https://tailwindcss.com/docs/margin/), [Text](https://tailwindcss.com/docs/text-color/), [Font](https://tailwindcss.com/docs/font-weight/), [Border](https://tailwindcss.com/docs/border-width), without writing a single CSS implementation Professional UI that conforms to the design draft. - -## Customized Utility Class - -We can also implement the new Utility Class ourselves to facilitate reuse between codes. - -Utility Class itself is also a **component-oriented** technology (using different classes on a component is equivalent to setting some attributes from the base class for this component), but the classname of Utility Class is global (because it is used on arbitrary components/elements), it is very suitable for implementation with separate CSS files. - -Create a new CSS file: - - - - -```bash -mkdir -p src/styles -touch src/styles/utils.css -``` - - - - -```powershell -mkdir -p src/styles -ni src/styles/utils.css -``` - - - - -Import `utils.css` in `src/routes/page.tsx`: - -```js -import '../styles/utils.css'; -``` - -A Utility Class named `custom-text-gray` is implemented in `src/routes/styles/utils.css`. - -```css -:root { - --custom-text-color: rgb(113, 128, 150); -} - -.custom-text-gray { - color: var(--custom-text-color); -} -``` - -:::info note -Modern.js integrates with [PostCSS](/guides/basic-features/css/css) and supports modern CSS syntax features such as [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties). - -::: - -Use in `src/components/Item/index.tsx`: - -```js -
-``` - -Change to: - -```js -
-``` - -Execute `pnpm run dev`, you can see that the font color has changed: - -![design2](https://lf3-static.bytednsdoc.com/obj/eden-cn/aphqeh7uhohpquloj/modern-js/docs/06/result3.png) - -:::info note -This is just to demonstrate Utility Class usage. In a real project, with Tailwind CSS, this Utility Class is of little value and should be added to the font color through the [**theme**](https://tailwindcss.com/docs/customizing-colors) of the configuration Design System. - -`utils.css` can also be written as `utils.scss` or `utils.less`, Modern.js out of the box support for SCSS and Less. - -However, with the support of PostCSS, modern CSS should be sufficient to meet these development needs, and the performance is also better than that of the preprocessor. It is recommended to use `.css` files first. - -:::