react-scripts to Vite in 5 minutes
Install NPM package modules
$ npm uninstall react-scripts
$ npm install -D vite @vitejs/plugin-react @vitejs/plugin-react-swc vite-plugin-svgr
Upgrade index.html
- Move public/index.html to root directory ./index.html
- Remove %PUBLIC_URL% from index.html
from
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
to
<link rel="icon" href="/favicon.ico" />
3. Add your index.jsx
to the end of file
...
<script type="module" src="src/index.jsx"></script>
</body>
</html>
Create 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"]
},
"exclude": ["node_modules"]
}
Create vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import svgr from 'vite-plugin-svgr';
export default defineConfig({
base: '/',
plugins: [react(), svgr()],
build: {
outDir: 'build'
}
})
Rename files if needed
If you have any React files with .js extension, change them to .jsx extension. For example,
$ mv index.js index.jsx
$ mv src/Header.js src/Header.jsx
Along with change, also change import statement to end with .jsx
. For example,
// import Header from './Header';
import Header from './Header.jsx';
Upgrade package.json scripts section
Before:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
After:
"scripts": {
"start": "vite",
"build": "vite build"
},
That’s it
After done the above, you will have files like the following
.
├── README.md
├── build
├── index.html
├── node_modules (directory)
├── package-lock.json
├── package.json
├── public (directory)
├── src (directory)
├── tsconfig.json
└── vite.config.ts
Now it’s time to test
$ vite
VITE v4.4.9 ready in 186 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h to show help
Open the browser, and check if it stars correctly. Hope all good.
Happy coding
Sep 28th, 2023
Allen Kim