Skip to main content
← Guides

Guide

How to Migrate from Create React App to Vite 2026

Updated PkgPulse Team12 min read
0

The definitive CRA to Vite migration guide for 2026. Every step, every gotcha, and how to handle the edge cases that trip up most migrations for 2026.

Contents

TL;DR

Move a client-rendered CRA app to Vite by replacing react-scripts, moving index.html to the project root, and switching client variables from process.env.REACT_APP_* to import.meta.env.VITE_*. The migration is ready when the production preview serves the app at its deployment base path, API calls work and the tests pass.

Key Takeaways

  • Development uses on-demand ES modules. Measure the first usable page and edit-to-screen time against your existing CRA app.
  • Migration checklist covers the build dependency, HTML entry, environment variables, TypeScript config and scripts.
  • Tests: CRA used Jest; switch to Vitest (see Jest → Vitest guide) or keep Jest standalone
  • CRA is deprecated for new apps. React recommends an existing app move to a framework or a build tool such as Vite.
  • TypeScript CRA: same migration, just add TypeScript-specific steps

Prerequisites and Assessment

Before you start, spend a few minutes auditing your current project. This assessment prevents surprises halfway through the migration.

Check your CRA version and scripts. Open package.json and look at the react-scripts version and the scripts block. CRA projects typically look like this:

{
  "dependencies": {
    "react-scripts": "5.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}

The pinned react-scripts 5.0.1 example uses webpack 5, Babel 7 and ESLint 8. Vite 8 serves application modules on demand in development, uses Oxc for the default TypeScript and JSX transforms, and uses Rolldown for dependency pre-bundling and production builds. Carry over any lint, test and transform settings that your project depended on CRA to provide.

The React team deprecated Create React App for new apps in February 2025. If your app needs server rendering, evaluate a React framework as part of the move. For a client-rendered app, Vite lets you keep the existing router and deployment model.

Inventory your dependencies. Check for these CRA-specific things that need attention:

  • process.env.REACT_APP_* env vars — these need renaming to VITE_*
  • SVG imports as React components — CRA had built-in support; Vite needs a plugin
  • public/index.html — this file moves to the project root in Vite
  • %PUBLIC_URL% template strings — these get stripped out
  • require() calls — CommonJS require() doesn't work in Vite's ESM environment without configuration
  • Jest tests — CRA wired up Jest automatically; Vite does not. You'll need to set up Vitest or configure Jest standalone.

Use this inventory to plan the migration. Projects that rely on webpack overrides through craco or react-app-rewired need to map those overrides to Vite configuration or plugins.


Step 1: Remove react-scripts and Install Vite

Start by uninstalling the CRA toolchain entirely. There is no partial migration — react-scripts and Vite cannot coexist as your primary build tool.

# Remove CRA
npm uninstall react-scripts

# Verify CRA is gone
grep "react-scripts" package.json  # Should show nothing

Use a Node release supported by the Vite version you install. For this Vite 8 migration, install Vite and its compatible React plugin. Commit the resolved lockfile so you can reproduce the build.

npm install -D vite@8 @vitejs/plugin-react@6

# For TypeScript projects without TypeScript installed:
npm install -D typescript

# Recommended extras:
npm install -D vite-plugin-svgr      # SVG as React components (if you use SVG imports)

With Vite 8, @vitejs/plugin-react v6 enables Fast Refresh through Oxc. If your CRA app relies on a custom Babel transform, port it explicitly with @rolldown/plugin-babel and test the affected code. Set resolve.tsconfigPaths: true to carry over aliases from tsconfig.json.

Update your package.json scripts:

{
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest run"
  }
}

The tsc && prefix makes type errors stop the build. For a JavaScript app without a TypeScript check, use vite build.


Step 2: Create vite.config.ts

Create vite.config.ts at the project root. This example preserves the dev port and output directory. Keep the optional plugins and proxy only if your app uses them.

// vite.config.ts — at project root
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import svgr from 'vite-plugin-svgr';  // Only if you import SVGs as React components

export default defineConfig({
  plugins: [
    react(),
    svgr(),            // Supports component imports such as ./logo.svg?react
  ],
  resolve: { tsconfigPaths: true },
  server: {
    port: 3000,       // Match CRA's default port
    open: true,       // Auto-open browser on dev start
    proxy: {
      // Proxy API calls to avoid CORS in development
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
    },
  },
  build: {
    outDir: 'build',   // CRA used 'build'; Vite defaults to 'dist' — match CRA
    sourcemap: true,
  },
});

Key decisions to understand in this config:

  • server.port: 3000 — CRA defaults to port 3000. Vite defaults to 5173. Set this explicitly so you don't break saved browser bookmarks or OAuth redirect URIs during development.
  • build.outDir: 'build' — CRA outputs to build/. Vite defaults to dist/. If your deployment pipeline references build/ (common in Netlify, Vercel, and CI scripts), keep this set to 'build'.
  • proxy — CRA's package.json "proxy" field had built-in proxy support. Vite's equivalent is server.proxy in vite.config.ts.

Step 3: Move index.html to the Project Root

CRA keeps index.html in the public/ directory. Vite expects it at the project root. This is the most structurally different change in the migration.

mv public/index.html ./index.html

After moving, edit index.html to make two changes: remove %PUBLIC_URL% prefixes and add the Vite module script entry point.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <!-- Before: href="%PUBLIC_URL%/favicon.ico" -->
    <!-- After: root-relative path, no variable -->
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <!-- Before: href="%PUBLIC_URL%/manifest.json" -->
    <link rel="manifest" href="/manifest.json" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!-- ADD THIS — Vite requires an explicit entry point script tag -->
    <!-- CRA injected this automatically; Vite requires it explicitly -->
    <script type="module" src="/src/index.tsx"></script>
    <!-- Use .tsx for TypeScript, .jsx for JavaScript -->
  </body>
</html>

The two critical changes are:

  1. All %PUBLIC_URL% occurrences become simple root-relative paths like /favicon.ico. Search and replace this across the entire file.
  2. The <script type="module" src="/src/index.tsx"> tag is essential. Without it, Vite has no entry point and the page will be blank.

Other files in public/ (images, icons, manifest.json, robots.txt) stay in public/ and Vite copies them to the output directory automatically.


Step 4: Rename Environment Variables

CRA required the REACT_APP_ prefix for custom environment variables. Vite uses VITE_. Any variable that does not have this prefix is not exposed to the browser bundle, which is a security feature — it prevents accidentally leaking server secrets.

Update your .env files:

# Before (.env, .env.local, .env.development, .env.production):
REACT_APP_API_URL=https://api.example.com
REACT_APP_GOOGLE_MAPS_KEY=abc123
REACT_APP_STRIPE_PUBLIC_KEY=pk_live_...

# After:
VITE_API_URL=https://api.example.com
VITE_GOOGLE_MAPS_KEY=abc123
VITE_STRIPE_PUBLIC_KEY=pk_live_...

Update all usages in your source code. The access pattern also changes — from process.env to import.meta.env:

// Before (CRA):
const apiUrl = process.env.REACT_APP_API_URL;
const mapsKey = process.env.REACT_APP_GOOGLE_MAPS_KEY;

// Check runtime environment:
if (process.env.NODE_ENV === 'development') {
  console.log('dev mode');
}
if (process.env.NODE_ENV === 'production') {
  // do something
}

// After (Vite):
const apiUrl = import.meta.env.VITE_API_URL;
const mapsKey = import.meta.env.VITE_GOOGLE_MAPS_KEY;

// Vite provides boolean flags instead of the string 'development':
if (import.meta.env.DEV) {
  console.log('dev mode');
}
if (import.meta.env.PROD) {
  // do something
}

// Mode is still available as a string if you need it:
if (import.meta.env.MODE === 'staging') {
  // custom mode
}

For TypeScript, add a src/vite-env.d.ts file to get proper type checking on your env vars:

// src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  readonly VITE_GOOGLE_MAPS_KEY: string;
  readonly VITE_STRIPE_PUBLIC_KEY: string;
  // Add all your VITE_ variables here for full type safety
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

This gives you autocomplete and type errors when you mistype an env variable name.


Step 5: Update tsconfig.json

CRA's tsconfig.json contains settings that are incompatible with Vite's build process. Replace it with a Vite-optimized configuration:

// tsconfig.json — Vite-compatible
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    // Key change: "bundler" resolution is Vite-native
    // CRA used "node" or "node16" — change this
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,

    // Vite handles transpilation; tsc only type-checks
    "noEmit": true,
    "jsx": "react-jsx",

    // Strict settings (keep from CRA):
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,

    // Add Vite's client types for import.meta.env
    "types": ["vite/client"]
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

Also create tsconfig.node.json for the Vite config file itself:

// tsconfig.node.json
{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}

The critical setting change is "moduleResolution": "bundler". CRA used "node" resolution which is CommonJS-oriented. "bundler" is designed for tools like Vite that use native ESM and allows importing TypeScript files with their .ts extensions explicitly.


Step 6: Handle SVG Imports

CRA had a built-in Webpack loader that let you import SVG files as React components using a named ReactComponent export. This is not a Web standard — it was CRA magic. Vite does not include this by default.

Install vite-plugin-svgr if you haven't already:

npm install -D vite-plugin-svgr

In a TypeScript app, put both reference directives at the top of src/vite-env.d.ts, above the ImportMetaEnv and ImportMeta declarations from the environment-variable step.

/// <reference types="vite/client" />
/// <reference types="vite-plugin-svgr/client" />

With the plugin configured in vite.config.ts, import the component with the ?react suffix.

// CRA: SVG as React component using named export
import { ReactComponent as Logo } from './assets/logo.svg';

// Vite with vite-plugin-svgr: use the ?react query parameter
import Logo from './assets/logo.svg?react';

// Usage is identical:
function Header() {
  return <Logo className="h-8 w-8" />;
}

If you just want to use an SVG as an image URL (not as a React component), Vite handles that natively without any plugin:

// Import SVG as a URL string — works in Vite without any plugin
import logoUrl from './assets/logo.svg';

function Header() {
  return <img src={logoUrl} alt="Logo" className="h-8 w-8" />;
}

Use the ?react pattern only when you need to manipulate the SVG's internals (changing colors via CSS, animating paths). For static logos and icons, the plain import is simpler.


Common Pitfalls

These are the issues that catch developers during migration and are not obvious from the documentation.

require() doesn't work. Vite runs in native ESM mode. CommonJS require() calls will throw a ReferenceError: require is not defined at runtime in the browser. Convert all require() to import:

// Before:
const config = require('./config.json');
const lodash = require('lodash');

// After:
import config from './config.json';
import lodash from 'lodash';

Node.js built-ins (require('path'), require('fs')) are server-side only and cannot run in the browser regardless of the bundler.

process.env is undefined. Vite does not polyfill process.env globally. Only import.meta.env works. If you use a library that internally references process.env.NODE_ENV, Vite will inline the value at build time — but your own code must use import.meta.env.

Jest tests break. CRA configured Jest with a custom transformer that handled JSX and TypeScript. When you remove react-scripts, Jest loses its configuration. You have two options: migrate to Vitest (the Vite-native test runner with a Jest-compatible API), or configure Jest manually with babel-jest or ts-jest. The Vitest migration is usually straightforward and worth doing at the same time.

Absolute imports stop working. If you use "paths": {"@/*": ["./src/*"]} in tsconfig.json, enable resolve.tsconfigPaths as shown in Step 2. Test an aliased import in both dev and the production build.

homepage in package.json. CRA read the homepage field to set the base URL for production builds. Vite uses base in vite.config.ts:

// vite.config.ts
export default defineConfig({
  base: '/my-app/',  // Replaces "homepage": "/my-app/" in CRA's package.json
});

Verification

After completing all steps, run these checks to confirm a successful migration:

# Start the dev server
npm run dev
# Open the URL Vite prints and load the main route

# Run type checking
npx tsc --noEmit
# Should show no TypeScript errors

# Build for production
npm run build
# Should complete with output in build/ for the config above

# Preview the production build locally
npm run preview
# Open the URL Vite prints and check routes and asset URLs

# Check for CRA remnants
grep -r "react-scripts\|REACT_APP_\|process\.env\.NODE_ENV\|%PUBLIC_URL%" src/
# Should return no matches

Review Vite’s chunk sizes after the build. If the initial route loads a large feature the user may never open, try a dynamic import() and check which chunks that route actually requests.


Understanding the Performance Difference

CRA runs a webpack compilation before serving its development bundle. Vite’s dev server serves index.html and transforms source modules as the browser requests them. It also pre-bundles dependencies, so timing when the server prints its URL misses some of the work needed to display the app.

Vite 8 uses Rolldown for production bundling. The standard Vite 7 pipeline used Rollup for production and esbuild for development transforms. Compare both the first usable page and Fast Refresh on the same CRA and Vite app. For production, compare the build time and the compressed JavaScript loaded by the same route.


Handling Tests After Migration

CRA configured Jest with a custom transformer that handled JSX and TypeScript automatically. When you remove react-scripts, Jest no longer knows how to parse .tsx files. You have two paths forward.

Option A: Migrate to Vitest. Vitest is Vite's test runner. It uses the same configuration and plugins as Vite, so it works out of the box with your vite.config.ts. The API is Jest-compatible, meaning describe, test, expect, vi.fn() (instead of jest.fn()), and vi.mock() (instead of jest.mock()) — most tests migrate with a global find-and-replace. Install it with npm install -D vitest @vitest/ui jsdom, add "test": "vitest" to your scripts, and add a test config to vite.config.ts:

// vite.config.ts — add test block
export default defineConfig({
  // ... existing config
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/setupTests.ts',
  },
});

Option B: Keep Jest standalone. If you have a large Jest test suite and want to avoid migrating at the same time as the Vite migration, configure Jest independently. Install @babel/preset-react, @babel/preset-typescript, babel-jest, and create a babel.config.js. This is more setup work but keeps your tests untouched.

Most teams find the Vitest migration straightforward enough to do at the same time as the Vite migration, since the API compatibility is high.


When to Choose Vite vs Other Alternatives

If your CRA project is growing into a larger application and you are evaluating your options beyond just "migrate to Vite," here is a quick comparison:

ScenarioBest Choice
Standard React SPA migration from CRAVite
Full-stack with API routes and SSRNext.js
Need Turbopack's incremental compilation for very large appsNext.js 15+
Monorepo with shared packagesVite + Turborepo
Electron desktop appVite (excellent Electron support)

For a CRA app that can stay client-rendered, start with Vite and run the verification checklist before removing the old deployment path. React’s migration guidance also lists other build tools and frameworks.


Source notes

Further Reading