创建时间: 2026-03-24最后更新: 2026-03-24

首先, 我们使用 vite 创建一个 React 项目

index.bash
1
npm create vite

上面的命令执行完成之后, 会引导你输入项目名称, 我们将项目名称取为:react19feature

index.bash
1
Project name: react19feature

输入之后, 按下回车, 选择前端框架

index.bash
1
vanilla
2
vue
3
> react
4
react-ts
5
preact
6
lit
7
svelte

我们选择 react, 执行完毕之后, vite 会在当前目录中创建项目 react19feature, 我们通过如下指令进入到项目文件

index.bash
1
cd react19feature

然后用编辑器打开项目文件, 在根目录的 package.json 文件中修改 reactreact-dom 的依赖版本为 react 19.

index.ts
1
"dependencies": {
2
"react": "^19.0.0",
3
"react-dom": "^19.0.0",
4
}
NOTE

注意:如果已经正式发版, 那么vite 创建的版本可能会直接更新为最新版而不需要我们手动修改

修改完成之后, 执行如下指令安装依赖

index.bash
1
npm i

然后执行如下指令运行项目

index.bash
1
npm run dev

成功启动之后, 我们可以在浏览器中输入 http://localhost:5173 访问到项目

预览

Vite + React

Edit src/App.tsx and save to test HMR

Click on the Vite and React logos to learn more

app.tsx
react.svg
vite.svg
01
import { useState } from 'react'
02
import reactLogo from './react.svg'
03
import viteLogo from './vite.svg'
04
05
function App() {
06
const [count, setCount] = useState(0)
07
08
return (
09
<div className='flex items-center justify-center flex-col p-4'>
10
<div className='flex items-center justify-center gap-4'>
11
<a href="https://vitejs.dev" target="_blank">
12
<img src={viteLogo.src} className="logo" alt="Vite logo" />
13
</a>
14
<a href="https://react.dev" target="_blank">
15
<img src={reactLogo.src} className="logo react" alt="React logo" />
16
</a>
17
</div>
18
<h1>Vite + React</h1>
19
<div className="text-center">
20
<button className='button' onClick={() => setCount((count) => count + 1)}>
21
count is {count}
22
</button>
23
<p>
24
Edit <code>src/App.tsx</code> and save to test HMR
25
</p>
26
</div>
27
<p className="read-the-docs">
28
Click on the Vite and React logos to learn more
29
</p>
30
</div>
31
)
32
}
33
34
export default App

由于我们项目需要用到 require, 但是 vite 中使用 ES module 作为模块方案, 因此并没有内置对CommonJS 的支持, 如果你需要在项目中支持 require 语法引入模块, 则需要做点其他的操作

首先, 我们需要安装如下依赖

index.bash
1
npm i vite-plugin-require-transform --save-dev

然后, 在 vite.config.js 中新增如下配置

vite.config.ts
01
import { defineConfig } from 'vite'
02
import react from '@vitejs/plugin-react-swc'
+
03
import requireTransform from 'vite-plugin-require-transform'
04
05
06
// https://vitejs.dev/config/
07
export default defineConfig({
08
plugins: [
09
react(),
+
10
requireTransform({
+
11
fileRegex: /.js$|.jsx$/,
+
12
}),
13
],
14
})
NOTE

如果你需要支持更多的文件后缀, 则需要在 fileRegex 中添加, 本项目仅支持 .js.jsx

最后重启项目即可.

除此之外, 如果你的项目中需要使用路由库, 我们可以安装 react-router

index.bash
1
npm i react-router

状态管理库 zustand

terminal
1
npm i zustand