How to Migrate from Create React App to Vite

A step-by-step guide to migrate a project from Create React App to Vite.

Step 1: Uninstall Create React App

Remove the react-scripts and react-app-rewired dependencies from your project:

npm uninstall react-scripts react-app-rewired

Step 2: Install Vite and React Plugin

Install Vite and the necessary plugin for React:

npm install vite @vitejs/plugin-react

Step 3: Set Up Vite Configuration

  1. Install empty-module and other required dependencies:

    npm install --save-dev empty-module buffer process
    
  2. Create a vite.config.ts file at the root of your project with the following content:

    import { defineConfig } from "vite";
    import react from "@vitejs/plugin-react";
    
    export default defineConfig({
      plugins: [react()],
      resolve: {
        alias: {
          crypto: "empty-module",
        },
      },
      define: {
        global: "globalThis",
      },
    });
    

Step 4: Updating index.html

Don’t forget: “This is a crucial step.”

  1. Move public/index.html to the root directory.
  2. Update index.html to include the necessary polyfills in the head:
    <head>
    <script type="module">
      import { Buffer } from "buffer";
      import process from "process";
      window.Buffer = Buffer;
      window.process = process;
    </script>
    </head>
    
  3. Finally, update the index.html to update the body to reference the main app
    <body>
    <script type="module" src="/src/index.tsx"></script>
    </body>
    

Step 5: Create Vite Environment Declaration

Create a vite-env.d.ts file in the src folder with:

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

Step 6: Update package.json Scripts

Replace the existing scripts with Vite commands:

{
  "scripts": {
    "start": "vite",
    "dev": "vite",
    "build": "tsc && vite build",
    "serve": "vite preview"
  }
}

Step 7: Update TypeScript Configuration

Update tsconfig.json to match Vite’s requirements:

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

Step 8: Fix Potential Errors

If you encounter a URI malformed error, remove all references to %PUBLIC_URL% in index.html.

Optional Cleanup

  • Remove config-overrides.js and react-app-env.d.ts files if they exist.

Following these steps will transition your project from Create React App to Vite, enhancing your development experience with a modern setup.