> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/rspeedy/styling.md.

# 样式

Rspeedy 支持多种方式来对你的应用程序进行样式设计，包括：

- [**CSS Modules**](#using-css-modules): 创建具有局部作用域的 CSS 类，以避免命名冲突并提高可维护性。

- [**Global CSS**](#using-global-css): 使用全局 CSS，对于习惯传统 CSS 的人来说很熟悉，但可能生成更大的 CSS 文件并且随着应用程序的增长难以管理样式。

- [**CSS pre-processors**](#using-css-pre-processors): 使用常见的 CSS 预处理器，如 [`sass`](https://sass-lang.com/) 或者 [`less`](https://lesscss.org/) 通过变量、嵌套规则等特性扩展了 CSS。

- [**PostCSS**](#using-postcss): 用于转换 CSS 的工具。

- [**Tailwind CSS**](#using-tailwind-css): 一个 CSS 框架，通过组合工具类（utility classes）快速进行自定义设计。

## 使用 CSS Modules \{#using-css-modules}

[CSS Modules](https://github.com/css-modules/css-modules) 允许以模块化的方式编写 CSS 代码，并且这些样式可以在 JavaScript 文件中被导入并使用。使用 CSS 模块可以自动生成唯一的类名，隔离不同模块之间的样式，并避免类名冲突。

:::tip
如果想要使用非隔离的 CSS 样式，可以使用 [Global CSS](#using-global-css)。
:::

Rspeedy 默认支持 CSS Modules，你不需要添加额外的配置。我们的约定是使用 `[name].module.css` 文件名来启用 CSS Modules。

### 示例

1. 与正常样式一样编写 CSS 代码

```css title=button.module.css
.red {
  background: red;
}
```

2. 像模块一样使用样式

```jsx title=Button.jsx
import styles from './button.module.css';

export function Button() {
  return (
    <view className={styles.red}>
      <text>Button</text>
    </view>
  );
}
```

或者使用 **Named Imports**:

```jsx title=Button.jsx
import { red } from './button.module.css';

export function Button() {
  return (
    <view className={red}>
      <text>Button</text>
    </view>
  );
}
```

### 配合 CSS Pre-Processor 使用

CSS Modules 也可以与 [CSS 预处理器](#using-css-pre-processors)一起使用。只需按照 `*.module.*` 的模式命名样式文件即可。

E.g.: 下面这些文件都将会被认为是 CSS Modules

- `*.module.css`
- `*.module.less`
- `*.module.sass`
- `*.module.scss`

### 识别规则

默认情况下，只有以 `*.module.{css,scss,less}` 结尾的文件才会被识别为 CSS Modules。

如果你想将其他 CSS 文件也视为 CSS Modules，可以通过在 Rspeedy 中配置 [output.cssModules.auto](/zh/api/rspeedy/rspeedy.cssmodules.auto.md) 来实现。

如下面的例子所示：

```js title=lynx.config.ts
import { defineConfig } from '@lynx-js/rspeedy';

export default defineConfig({
  output: {
    cssModules: {
      auto(filename) {
        return filename.includes('.module.') || filename.includes('/shared/');
      },
    },
  },
});
```

给定此配置，以下 imports 将被识别为 CSS Modules：

```js
import * as foo from './foo.module.css';
import * as bar from './shared/bar.css';
```

### 类型声明

当你在 TypeScript 代码中导入 CSS Modules 时，TypeScript 可能会提示该模块缺少类型定义：

```
TS2307: Cannot find module './index.module.css' or its corresponding type declarations.
```

要解决这个问题，你需要为 CSS 模块添加一个类型声明文件，请创建一个 `src/rspeedy-env.d.ts` 文件，并添加相应的类型声明。

```ts
/// <reference types="@lynx-js/rspeedy/client" />
```

:::tip
[`create-rspeedy`](https://www.npmjs.com/package/create-rspeedy) 会自动为你创建这个文件。
:::

如果在添加类型声明后仍然存在类型错误，你可以尝试重启当前的 IDE，以确保 TypeScript 能正确识别类型定义。

#### 生成 TS 类型定义

`@lynx-js/rspeedy/client` 将提供如下类型声明：

```ts
declare module '*.module.css' {
  type CSSModuleClasses = {
    readonly [key: string]: string;
  };
  const classes: CSSModuleClasses;
  export default classes;
}
```

它对于每个 CSS Modules 中含有的类名不够精确。

使用 [Typed CSS Modules Plugin](https://v0.rsbuild.rs/plugins/list/plugin-typed-css-modules) 将为所有 CSS Modules 生成具有精确类型声明的类型声明文件。

1. 安装 `@rsbuild/plugin-typed-css-modules`


```sh [npm]
npm add -D @rsbuild/plugin-typed-css-modules
```

```sh [yarn]
yarn add -D @rsbuild/plugin-typed-css-modules
```

```sh [pnpm]
pnpm add -D @rsbuild/plugin-typed-css-modules
```

```sh [bun]
bun add -D @rsbuild/plugin-typed-css-modules
```

```sh [deno]
deno add -D npm:@rsbuild/plugin-typed-css-modules
```

2. 将 `pluginTypedCSSModules` 添加至 `lynx.config.ts`

```js title=lynx.config.ts
import { pluginTypedCSSModules } from '@rsbuild/plugin-typed-css-modules';

import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin';
import { defineConfig } from '@lynx-js/rspeedy';

export default defineConfig({
  source: {
    entry: './src/index.tsx',
  },
  plugins: [pluginReactLynx(), pluginTypedCSSModules()],
});
```

在执行 `rspeedy build` 或者 `rspeedy dev` 后，将会自动生成详细的类型定义。

```ts title=button.module.css.d.ts
// This file is automatically generated.
// Please do not change this file!
interface CssExports {
  red: string;
}
export const cssExports: CssExports;
export default cssExports;
```

你还需要设置 [`"allowArbitraryExtensions": true`](https://www.typescriptlang.org/tsconfig/#allowArbitraryExtensions) 以及 [`"moduleResolution": "Bundler"`](https://www.typescriptlang.org/tsconfig/#moduleResolution) 来让 TypeScript 正确工作。

```json title=tsconfig.json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "allowArbitraryExtensions": true
  }
}
```

## 使用 Global CSS \{#using-global-css}

在某些情况下，你可能希望 CSS 样式与一些复杂的选择器一起使用，或者一些样式能够被所有 JSX 所使用。这在 Rspeedy 中被称为全局 CSS。

只需编写 CSS 代码，并从 JavaScript 文件中导入即可。

### 示例

1. 像往常一样编写 CSS 文件

```css title=styles.css
.red {
  background: red;
}

.red > text {
  color: blue;
}
```

2. 从 JSX 中引入 CSS 并指定类名

```jsx title=index.jsx
import './styles.css';

export default function App() {
  return (
    <view className="red">
      <text>Hello, Rspeedy!</text>
    </view>
  );
}
```

## 使用 CSS Pre-Processors \{#using-css-pre-processors}

CSS 预处理器通过变量、嵌套规则等特性扩展了 CSS。

### 使用 `sass`

只需创建 `.scss` 或 `.sass` 文件，并将它们导入到 JavaScript 中即可。

```jsx
import './global.sass';
import styles from './button.module.scss';

export function App() {
  return (
    <view className={styles.red}>
      <text className="title">Hello, Sass</text>
    </view>
  );
}
```

1. 安装 `@rsbuild/plugin-sass`


```sh [npm]
npm install -D @rsbuild/plugin-sass
```

```sh [yarn]
yarn add -D @rsbuild/plugin-sass
```

```sh [pnpm]
pnpm add -D @rsbuild/plugin-sass
```

```sh [bun]
bun add -D @rsbuild/plugin-sass
```

```sh [deno]
deno add -D npm:@rsbuild/plugin-sass
```

2. 将 `pluginSass` 添加至 `lynx.config.ts`

```js title=lynx.config.ts
import { pluginSass } from '@rsbuild/plugin-sass';

import { defineConfig } from '@lynx-js/rspeedy';

export default defineConfig({
  source: {
    entry: './src/index.tsx',
  },
  plugins: [
    pluginSass({
      /** sass options */
    }),
  ],
});
```

在 `pluginSass` 中可以使用更多选项，请参阅 [Sass 插件](https://rsbuild.rs/plugins/list/plugin-sass)以了解用法。

### 使用 `less`

只需创建 `.less` 文件，并将它们导入到 JavaScript 中即可。

```jsx
import './global.less';
import styles from './button.module.less';

export function App() {
  return (
    <view className={styles.red}>
      <text className="title">Hello, Less</text>
    </view>
  );
}
```

1. 安装 `@rsbuild/plugin-less`


```sh [npm]
npm install -D @rsbuild/plugin-less
```

```sh [yarn]
yarn add -D @rsbuild/plugin-less
```

```sh [pnpm]
pnpm add -D @rsbuild/plugin-less
```

```sh [bun]
bun add -D @rsbuild/plugin-less
```

```sh [deno]
deno add -D npm:@rsbuild/plugin-less
```

2. 将 `pluginLess` 添加至 `lynx.config.ts`

```js title=lynx.config.ts
import { pluginLess } from '@rsbuild/plugin-less';

import { defineConfig } from '@lynx-js/rspeedy';

export default defineConfig({
  source: {
    entry: './src/index.tsx',
  },
  plugins: [
    pluginLess({
      /** less options */
    }),
  ],
});
```

在 `pluginLess` 中可以使用更多选项，请参阅 [Less 插件](https://rsbuild.rs/plugins/list/plugin-less)以了解用法。

## 使用 PostCSS \{#using-postcss}

由 Rsbuild 提供支持的 Rspeedy 内置了 [PostCSS](https://postcss.org/) 用于转换 CSS 代码。

Rsbuild 使用 `postcss-load-config` 从当前项目的根目录加载 PostCSS 配置文件，例如 `postcss.config.js`：

```js
export default {
  'postcss-px-to-viewport': {
    viewportWidth: 375,
  },
};
```

## 使用 Tailwind CSS \{#using-tailwind-css}

:::tip Tailwind CSS v3
Lynx 目前需要 **Tailwind CSS v3**。请安装 `tailwindcss@^3` 并将其用作 PostCSS 插件。注意 v4 的包如 `@tailwindcss/postcss`、`@tailwindcss/vite` 和 `@tailwindcss/cli` 与 `@lynx-js/tailwind-preset` 不兼容。
:::

1. 安装 Tailwind CSS

   Rspeedy 内置支持 PostCSS，你可以安装 tailwindcss 包来接入 Tailwind CSS：

   <PackageManagerTabs command="install -D tailwindcss@^3" />

2. 配置 PostCSS

   你可以通过 [`postcss.config.js`](https://www.npmjs.com/package/postcss-loader#config) 或 [`tools.postcss`](https://rsbuild.rs/zh/config/tools/postcss) 来注册 `tailwindcss` 的 PostCSS 插件。

   ```js title=postcss.config.js
   export default {
     plugins: {
       tailwindcss: {},
     },
   };
   ```

3. 安装 `@lynx-js/tailwind-preset` 包：

   <PackageManagerTabs command="install -D @lynx-js/tailwind-preset" />

4. 配置 `tailwind.config.js` 并添加 `@lynx-js/tailwind-preset`：

   您必须使用 [`@lynx-js/tailwind-preset`](https://github.com/lynx-family/lynx-stack/tree/main/packages/tailwind-preset) 删除 Lynx 中不支持的所有 tailwindcss 工具类或替换至特定于 Lynx 的替代方案。

   ```js title=tailwind.config.js
   import lynxPreset from '@lynx-js/tailwind-preset';

   export default {
     content: ['./src/**/*.{js,ts,jsx,tsx}'],
     presets: [lynxPreset],
   };
   ```

   :::warning

   `@lynx-js/tailwind-preset` 仍不稳定，请谨慎使用。如果您发现任何 tailwindcss 功能无法使用且应予以支持，请在 [https://github.com/lynx-family/lynx-stack/issues](https://github.com/lynx-family/lynx-stack/issues) 上提出 issue。

   :::

### 使用示例

**下面是一个示例: tailwindcss**

**Entry:** `src`
**Bundle:** `dist/main.lynx.bundle` | Web: `dist/main.web.bundle`

```tsx
import { useEffect } from "@lynx-js/react";

import "./App.css";

export function App() {
  useEffect(() => {
    console.info("Hello, ReactLynx");
  }, []);

  return (
    <page>
      <view className="flex flex-col justify-center items-center min-h-screen text-center">
        <text className="text-6xl font-bold leading-normal underline">
          ReactLynx + TailwindCSS
        </text>
        <text className="text-lg font-normal text-gray-500 leading-normal">
          Start building amazing things with ReactLynx.
        </text>
        <view
          className="flex flex-row p-20 rounded-full"
          style={{
            backgroundColor: "rgba(255, 255, 255, 0.5)",
            padding: "40px",
            margin: "10px",
          }}
        >
          <image
            src="https://images.unsplash.com/photo-1554629947-334ff61d85dc?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=320&h=320&q=80"
            className="mt-8 rounded-full w-16 h-16 translate-x-6"
            style={{
              marginRight: "40px",
            }}
          />
          {/* static should not be supported */}
          <image
            src="https://images.unsplash.com/photo-1554629947-334ff61d85dc?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=320&h=320&q=80"
            className="mt-8 rounded-full w-16 h-16 rotate-45 static"
            style={{
              marginRight: "40px",
            }}
          />
          {/* static should be supported */}
          <image
            src="https://images.unsplash.com/photo-1554629947-334ff61d85dc?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=320&h=320&q=80"
            className="mt-8 rounded-full w-16 h-16 scale-150 sticky"
            style={{
              marginRight: "40px",
            }}
          />
        </view>
        <view className="grid grid-cols-3 gap-4">
          <text>01</text>
          <text>02</text>
          <text>03</text>
          <text>04</text>
          <text>05</text>
          <text>06</text>
        </view>
      </view>
    </page>
  );
}

```


