---
title: "React"
locale: "zh"
version: "current"
canonicalUrl: "https://farmfe.org/zh/docs/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';
import react from '@farmfe/plugin-react';

export default defineConfig({
  plugins: [react()],
});
```


和 JS 插件一样，导入 ` @farmfe/plugin-react ` 并以工厂函数的形式调用即可注册。


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


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


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

export default defineConfig({
  compilation: {
    script: {
      plugins: [
        {
          name: '@swc/plugin-emotion',
          options: {},
          filters: {
            moduleTypes: ['tsx'],
          },
        },
      ],
    },
  },
  plugins: [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 react from '@farmfe/plugin-react';
import farmJsPluginSvgr from '@farmfe/js-plugin-svgr';

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


开发环境时运行


**npm**

```sh
npm run dev
```

**pnpm**

```sh
pnpm run dev
```

**yarn**

```sh
yarn run dev
```

**bun**

```sh
bun run dev
```


在生产环境下进行打包


**npm**

```sh
npm run build
```

**pnpm**

```sh
pnpm run build
```

**yarn**

```sh
yarn run build
```

**bun**

```sh
bun run build
```


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


**npm**

```sh
npm run preview
```

**pnpm**

```sh
pnpm run preview
```

**yarn**

```sh
yarn run preview
```

**bun**

```sh
bun run preview
```


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