从 create-react-app 迁移到 Vite:快速简易指南

2025-05-28

从 create-react-app 迁移到 Vite:快速简易指南

最近,React 不再推荐使用 create-react-app (CRA) 作为新项目的起点。相反,它现在鼓励开发人员在大多数项目中使用框架。但是,对于较小的项目,可能不需要一个成熟的框架。在这种情况下,Vite成为一个有前途的选择。Vite 不是像 Next.js 或 Remix 这样的框架,但它提供了一些特性,使其成为小型项目(例如个人作品集,就像我的投资组合)的绝佳选择。在这篇博文中,我们将引导您完成从 create-react-app 迁移到 Vite 的步骤,以完成您的下一个项目。

迁移步骤

这些迁移步骤假设我们有一个带有 Typescript 的 CRA 项目。

  1. 删除 CRA
  2. 安装 Vite 依赖项
  3. 移动 index.html
  4. 添加 vite.config.ts
  5. 添加 vite-env.d.ts
  6. 添加 vite 脚本
  7. 修复 tsconfig.json
  8. 从 Jest 迁移到 Vitest
  9. 额外的

步骤 1 - 移除 CRA

第一步是从您的项目中卸载 create-react-app。

npm uninstall react-scripts
Enter fullscreen mode Exit fullscreen mode

第 2 步 - 安装 Vite 依赖项

接下来,安装 Vite 所需的依赖项。

npm install vite @vitejs/plugin-react-swc vite-tsconfig-paths vite-plugin-svgr
Enter fullscreen mode Exit fullscreen mode

注意:根据您的具体需求,您可以从官方 Vite 插件文档中选择不同的插件。

步骤 3 - 移动 index.html

create-react-app 使用 public/index.html 作为默认入口,而 Vite 会在根目录下查找 index.html。要进行转换,请将 index.html 移至根目录,并相应地更新脚本标签。

<!-- index.html -->
<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>

  <script type="module" src="/src/index.tsx"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

步骤 4 - 添加 vite.config.ts

在项目根目录创建一个 vite.config.ts 文件,其内容如下:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/',
  plugins: [react()]
})
Enter fullscreen mode Exit fullscreen mode

步骤 5 - 添加 vite-env.d.ts

在 src 文件夹中创建一个 vite-env.d.ts 文件,其内容如下:

/// <reference types="vite/client" />

Enter fullscreen mode Exit fullscreen mode

步骤 6 - 添加 vite 脚本

将 package.json 中现有的 CRA 脚本替换为 Vite 脚本。

 "scripts": {
    "start": "vite",
    "build": "tsc && vite build",
    "serve": "vite preview"
}
Enter fullscreen mode Exit fullscreen mode

步骤 7 - 修复 tsconfig.json

将您的 tsconfig.json 更新为最终版本。

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "jsx": "react-jsx",
    "types": ["vite/client", "vite-plugin-svgr/client"]
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

步骤 8 - 从 Jest 迁移到 Vitest

在我们迁移到 Vite 的过程中,另一个好主意是考虑从 Jest 迁移到Vitest。步骤如下:

8.1 - 安装 Vitest 依赖项:

npm i -D jsdom vitest @vitest/coverage-v8
Enter fullscreen mode Exit fullscreen mode

8.2 - 更新 vite.config.ts 以包含 Vitest 配置:

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/',
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/setupTests.ts',
    css: true,
    reporters: ['verbose'],
    coverage: {
      reporter: ['text', 'json', 'html'],
      include: ['src/**/*'],
      exclude: [],
    }
  },
})
Enter fullscreen mode Exit fullscreen mode

8.3 - 使用 Vitest 脚本更新 package.json:

  "scripts": {
    "start": "vite",
    "build": "tsc && vite build",
    "serve": "vite preview",
    "test": "vitest",
    "test:coverage": "vitest run --coverage --watch=false"
  },
Enter fullscreen mode Exit fullscreen mode

步骤 9 - 附加功能

如果您使用 GitHub Actions 将代码推送到 GitHub Pages,则需要更新工作流文件,因为 Vitedist在我们运行时会生成一个文件夹npm run build

name: GitHub Pages

on:
  push:
    branches:
      - master
  pull_request:

jobs:
  deploy:
    runs-on: ubuntu-22.04
    permissions:
      contents: write
    concurrency:
      group: ${{ github.workflow }}-${{ github.ref }}
    steps:
      - uses: actions/checkout@v3

      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: "16"

      - name: Cache dependencies
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - run: npm ci
      - run: npm run build

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        if: github.ref == 'refs/heads/master'
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist

Enter fullscreen mode Exit fullscreen mode

完成这些步骤后,您应该已经成功将 create-react-app 项目迁移到 Vite,享受其优势并优化小型项目的开发流程。祝您编程愉快!

文章来源:https://dev.to/henriquejensen/migration-from-create-react-app-to-vite-a-quick-and-easy-guide-5e72
PREV
使用 React Error Boundary 优雅地处理错误
NEXT
全球人才签证:如何在没有雇主的情况下移居英国