Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Testing and Tooling

Migrating to Vite and Troubleshooting

Move a webpack or Create React App project to Vite step by step, then diagnose the errors people hit most: CommonJS, env variables, aliases, HMR, CORS and slow starts.

Most developers meet Vite not on a new project but on an old one: a Create React App, a webpack setup or a Vue CLI project with a slow dev server. Moving is usually manageable, and the payoff (start-up in under a second, faster hot updates) is immediate. This lesson gives a migration checklist and then a field guide to the errors you are most likely to see.

Config and shell commands are real and read-only. The stand-ins are small tools you could use during a migration: a scanner for problem patterns and a CommonJS-to-ESM sketch.

Migration checklist

  1. Install Vite and the framework plugin. npm install -D vite @vitejs/plugin-react (or plugin-vue), then remove the old build tool and its config (react-scripts, webpack*, babel presets you no longer need).

  2. Move index.html to the project root and add a module script:

    HTML
    <div id="root"></div>
    <script type="module" src="./src/index.jsx"></script>
    

    CRA kept index.html in public/ with %PUBLIC_URL% placeholders. Vite uses the file in the root as the entry; remove the placeholders and use plain absolute paths like /favicon.ico.

  3. Create vite.config.js with the plugin, aliases and a dev server.port that matches your old one.

  4. Rename JSX files to .jsx (or .tsx). Vite does not parse JSX in .js files by default.

  5. Replace environment variables. process.env.REACT_APP_API becomes import.meta.env.VITE_API, and the file variables are renamed to VITE_*.

  6. Update scripts in package.json:

    JSON
    { "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" } }
    
  7. Fix imports that depended on webpack features (see below).

  8. Move tests to Vitest (the API is Jest-compatible: change jest.fn to vi.fn).

  9. Run the build and compare bundle sizes and behavior; test in a real browser.

Replacing webpack-only features

webpack / CRA Vite
require.context('./dir', true, /\.js$/) import.meta.glob('./dir/**/*.js')
process.env.NODE_ENV import.meta.env.MODE / import.meta.env.PROD
require('./x.json') import x from './x.json'
import logo from './logo.svg' gives URL Same, gives a URL; ?raw gives text, ?url forces URL
SVGR ReactComponent import vite-plugin-svgr and ?react suffix
DefinePlugin define option in config
Loader chain file-loader, url-loader Built in, nothing to install
resolve.modules resolve.alias and tsconfig paths
JavaScript
// real Vite: loading many files without require.context
const modules = import.meta.glob('./pages/*.jsx');          // lazy: functions returning promises
const eager = import.meta.glob('./icons/*.svg', { eager: true, query: '?url', import: 'default' });
JS Stand-in: scan source for migration problems

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Field guide to common errors

"Uncaught ReferenceError: process is not defined" / "require is not defined". Browser code has no process or require. Replace with import.meta.env and ESM imports. For a dependency that insists on process.env.NODE_ENV, Vite already replaces that at build time; for other keys use define: { 'process.env.FOO': JSON.stringify('x') }.

"Failed to resolve import './Button' ... Does the file exist?" Casing matters on Linux and macOS servers even if Windows ignores it. Check file name case exactly. Also check the extension: Vite resolves .js, .ts, .jsx, .tsx, .json without one, but not .vue unless you add it to resolve.extensions.

"The JSX syntax extension is not currently enabled". The file is .js. Rename it to .jsx.

CommonJS dependency has no default export / X is not a constructor. Vite pre-bundles dependencies in dev, usually fixing interop, but a mismatch between dev and build can appear. Add the package to optimizeDeps.include, or use an ESM version of the library. In build, build.commonjsOptions tunes the CommonJS plugin.

HMR does not update, or the full page reloads. A module that exports both components and other values breaks React Fast Refresh. Move non-component exports to another file. Circular imports can also force a full reload.

CORS errors in dev. Do not enable CORS on the API just for development: use server.proxy so requests are same-origin (see Backend Integration).

Environment variable is undefined. It lacks the VITE_ prefix, the .env file was changed without restarting the dev server, or the mode does not match (.env.production is only read in build mode).

Blank page after deploy. Wrong base for a sub-folder, or the server does not rewrite deep routes to index.html for a single-page app. Configure a fallback rule on the host.

Slow first start or constant "optimized dependencies changed, reloading". A dependency was discovered late. Add it to optimizeDeps.include, and delete node_modules/.vite if the cache is stale.

"Cannot find module" in vite.config.ts using __dirname. Config files run as ESM. Use import.meta.dirname (Node 20.11+) or fileURLToPath(new URL('.', import.meta.url)).

JS Stand-in: CommonJS to ESM sketch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Debugging approach

  1. Read the first error message in the terminal and the browser console; fix the top one.
  2. Reproduce with vite build and vite preview to separate dev-only issues from build issues.
  3. Use vite --debug for detailed logs, and vite-plugin-inspect to see transforms.
  4. Delete node_modules/.vite (the dependency cache) and restart.
  5. Bisect: disable plugins one by one.
  6. Search the exact message together with the plugin name; most migration problems are common.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the entry index.html live in a Vite project?

    Vite treats the root index.html as the entry and follows its script tags.
  2. 2. What replaces require.context in Vite?

    import.meta.glob imports a set of files matching a pattern, lazily or eagerly.
  3. 3. An env variable is undefined in the browser. What is the likeliest cause?

    Only VITE_-prefixed variables are exposed, and .env files are read at start-up.
  4. 4. How do you avoid CORS errors in dev when calling an API on another port?

    A proxy forwards /api calls through the dev server, so the browser sees one origin.

Summary

  • Migration steps: install Vite and plugin, move index.html to the root, rename JSX files, switch env variables to VITE_*, update scripts and tests.
  • Replace webpack-only features: import.meta.glob, define, built-in asset handling.
  • Most errors are about CommonJS, env variables, casing, JSX in .js files, base paths and server fallbacks.
  • Separate dev problems from build problems with vite build and vite preview.
  • When stuck: clear node_modules/.vite, inspect transforms, disable plugins one by one.

Next: Project: A Component Library