Sometime back I started working with Vite and enjoyed it so much, that I stopped using create-react-app
on any new apps. However, I had some older applications that were still using CRA and would face some issues when updating packages and attempting to audit and fix vulnerabilities.
Specifically, the react-scripts
package had some minor issues/inconveniences (see this issue). So I decided to migrate my CRA apps to use Vite instead.
These are the steps that have worked for me!
1. Delete node_modules
folder
First you want to delete the node_modules folder, otherwise when installing Vite, you may get an error “ENOTEMPTY: directory not empty”.
2. Install dependencies
Install Vite and the react plugin for Vite, both as devDependencies.
npm install --save-dev vite @vitejs/plugin-react
3. Create vite.config.js
file
You will need to create the vite.config.js
file, then configure the react plugin.
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
});
4. Move index.html
to root
CRA sets up the index.html
file under the /public
folder, but for Vite, add it at the root of your app.
5. Update the new index.html
file
In the new index html file, add the script file pointing to the entry point of your app, and be sure to set type to module and that the file extension is JSX.
Also remove all references to %PUBLIC_URL%
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.jpg" />
<link rel="manifest" href="/manifest.json" />
<title>My Vite APP!</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.jsx"></script>
</body>
</html>
6. Uninstall react-scripts
At this point, you can uninstall react-scripts
!
7. Rename JS to JSX (if needed)
In case you are not using JSX already, you will need to rename the file extensions. Vite recommends the use of JSX files. You can use something like the following:
find . -iname "\*.js" -exec bash -c 'mv "$0" "${0%\.js}.jsx"' {} \;
If you need to use JS files, you can configure Vite to do so.
8. Update scripts
Update the scripts in package.json
to use Vite.
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
Run your app!
At this point, you should be able to run your app successfully.