---
title: "React"
locale: "zh"
version: "1.x"
canonicalUrl: "https://farmfe.org/zh/docs/1.x/frameworks/react"
publicationStatus: "prerelease"
---

<a id="react"></a>
# React


基于 ` Farm ` 创建一个 ` React ` 项目。


` Farm ` 提供两种方案来支持创建 ` React ` 项目:


- 使用 ` create-farm ` 脚手架创建脚手架项目
- 你可以根据当前文档手动创建一个 ` React ` 项目


<a id="创建-react-项目"></a>
### 创建 React 项目


**npm**

```sh
npm create farm@latest
```

**pnpm**

```sh
pnpm create farm@latest
```

**yarn**

```sh
yarn create farm@latest
```

**bun**

```sh
bun create farm@latest
```


在 ` Select Framework ` 中选择 ` React ` 模版


` Farm ` 需要通过注册 ` @farmfe/plugin-react ` 插件来对 ` React ` 项目进行支持。


```javascript
import { defineConfig } from '@farmfe/core';

export default defineConfig({
  plugins: ['@farmfe/plugin-react'],
});
```


` @farmfe/plugin-react ` 插件由 ` Rust ` 编写, 因此你不需要显式引入, 通过传递一个字符串包名即可注册。


<a id="集成-emotion"></a>
### 集成 ` emotion `


你可以通过注册 ` @swc/plugin-emotion ` 插件来对 ` emotion ` 进行支持。


```javascript
import { defineConfig } from '@farmfe/core';

export default defineConfig({
  compilation: {
    script: {
      plugins: [
        {
          name: '@swc/plugin-emotion',
          options: {},
          filters: {
            moduleTypes: ['tsx'],
          },
        },
      ],
    },
  },
  plugins: [['@farmfe/plugin-react', { "runtime": "automatic", "importSource": "@emotion/react" }]],
});

```


```javascript
import { css } from '@emotion/react';

const color = 'white';

export function Main() {
  return (
    <div
      onClick={() => setCount((c) => c + 1)}
      css={css`
        padding: 32px;
        background-color: hotpink;
        font-size: 24px;
        border-radius: 4px;
        &:hover {
          color: ${color};
        }
      `}
    >
      {a}: {count}
    </div>
  );
}
```


<a id="集成-svgr"></a>
### 集成 ` svgr `


SVGR 是一个用于将 SVG 转换为 React 组件的工具，Farm 提供了 Js 插件来支持 SVGR。


```javascript
import { defineConfig } from '@farmfe/core';
import farmJsPluginSvgr from '@farmfe/js-plugin-svgr';

export default defineConfig(async (env) => {
  return {
    plugins: [
      [
        '@farmfe/plugin-react',
        {
          refresh: process.env.NODE_ENV === 'development',
          development: process.env.NODE_ENV === 'development'
        }
      ],
      farmJsPluginSvgr()
    ]
  };
});

开发环境时运行

<PackageManagerTabs command="npm run dev" />

在生产环境下进行打包

<PackageManagerTabs command="npm run build" />

预览生产环境打包之后构建的产物

<PackageManagerTabs command="npm run preview" />


如若想查看示例详情: [React 示例](https://github.com/farm-fe/farm/tree/main/examples/react)
```
