将使用create-react-app创建的应用迁移至vite
据说 create-react-app 不再维护了,而 react-scripts 也妨碍了 TypeScript 的升级至5及以上版本。因此,需要将由 create-react-app 创建的应用迁移到 Vite。
更新后会出现以下错误。
$ npm update
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-scripts@5.0.1
npm ERR! Found: typescript@5.3.2
npm ERR! node_modules/typescript
npm ERR! typescript@"^5.3.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm ERR! node_modules/react-scripts
npm ERR! react-scripts@"5.0.1" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: typescript@4.9.5
npm ERR! node_modules/typescript
npm ERR! peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm ERR! node_modules/react-scripts
npm ERR! react-scripts@"5.0.1" from the root project
听说Vite在法语中意为”快速”,在日语中发音似乎是”ヴィート”(实际上听起来像”ルフィーツ”)。据说是由开发Vue.js的人开发的,总之非常快速。详细信息请看这里。
这是基于这个模板创建的。
npx create-react-app my-app --template typescript
首先安装Vite。
npm install --save-dev vite @vitejs/plugin-react
卸载 react-scripts。
npm uninstall react-scripts
安装 TypeScript。
npm install typescript@5.3.2
以下是更新后的 package.json。请将 npm script 替换为 vite。
"dependencies": {
- "react-scripts": "5.0.1",
- "typescript": "^4.9.5",
+ "typescript": "^5.3.2",
},
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
+ "start": "vite",
+ "build": "tsc && vite build",
+ "preview": "vite preview",
},
"devDependencies": {
+ "@vitejs/plugin-react": "^4.2.0",
+ "vite": "^5.0.4"
}
}
由于只有这些是不足以在本地启动或构建的,所以还需要修复文件。
在项目根目录下创建`vite.config.ts`文件。将构建后的目录名称命名为’react’,并将其设为’build’(默认为’dist’)。
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
outDir: 'build',
},
});
将public/index.html文件移至项目的根目录进行修正,删除%PUBLIC_URL%。
<html lang="en">
<head>
- <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+ <link rel="icon" href="/favicon.ico" />
- <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+ <link rel="apple-touch-icon" href="/logo192.png" />
- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+ <link rel="manifest" href="/manifest.json" />
<body>
<div id="root"></div>
+ <script type="module" src="/src/index.tsx"></script>
如果环境变量是在 create-react-app 中,那么以 REACT_APP 开头,但是在 vite 中则变为以 VITE_ 开头。详细信息请参阅此处。
-/// <reference types="react-scripts" />
+/// <reference types="vite/client" />
如果能到这一步,可以进行构建并预览。预览可以参考构建后的文件并确认显示情况,可以进行接近正式环境的操作确认。
npm run build
npm run preview