Migrate CRA to Vite Without Changing Any Old Files
The Back Story about this Metaphor
Migrate CRA to Vite Without Changing Any Old Files
Metaphore story
When I need more speed in development phase, I choose Vite to boost my development workflow. But I have old (slow) CRA before.
Here my old CRA Directory Structure
1whats-my-app/ 2 README.md 3 .env 4 node_modules/ 5 package.json 6 public/ 7 index.html 8 favicon.ico 9 src/ 10 assets/ 11 components/ 12 utils/ 13 App.js 14 index.css 15 index.js
But wait... Vite work out of the book using .tsx
and .jsx
when first initial create vite app. But my old metaphor
have .js
extension and I don't want to rename and changing my old metaphor
base.
So, here the step to chill and migrate...
- Create file
vite.config.js
in the root directory
1import { defineConfig, loadEnv } from 'vite'; 2import react from '@vitejs/plugin-react'; 3import fs from 'fs/promises'; 4 5// https://vitejs.dev/config/ 6export default ({ mode }) => { 7 process.env = Object.assign(process.env, loadEnv(mode, process.cwd(), '')); 8 9 return defineConfig({ 10 build: { 11 outDir: 'build', 12 }, 13 server: { 14 port: process.env.VITE_PORT, 15 }, 16 esbuild: { 17 loader: 'jsx', 18 include: /src\/.*\.jsx?$/, 19 exclude: [], 20 }, 21 optimizeDeps: { 22 esbuildOptions: { 23 plugins: [ 24 { 25 name: 'load-js-files-as-jsx', 26 setup(build) { 27 build.onLoad({ filter: /src\/.*\.js$/ }, async (args) => ({ 28 loader: 'jsx', 29 contents: await fs.readFile(args.path, 'utf8'), 30 })); 31 }, 32 }, 33 ], 34 }, 35 }, 36 plugins: [react()], 37 }); 38};
- Remove all
react-scripts
command and package inpackage.json
1{ 2 "scripts": { 3 "dev": "vite", 4 "build": "vite build", 5 "preview": "vite preview" 6 } 7}
- Move
index.html
frompublic
directory to root of project, and also make sure:
1<!DOCTYPE html> 2<html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <link rel="icon" type="image/svg+xml" href="/logo/logo.png" /> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 7 <title>Vite + React</title> 8 </head> 9 <body> 10 <div id="root"></div> 11 <!--- include your src/index.js file here ---> 12 <script type="module" src="/src/index.js"></script> 13 </body> 14</html>
- Change
env
variable prefixREACT_APP_
withVITE_
- Install
vite
as dev dependenciesnpm i --save-dev @types/react @types/react-dom @vitejs/plugin-react vite
Here my new directory structure
1whats-my-app/ 2 README.md 3 .env 4 node_modules/ 5 package.json 6 public/ 7 favicon.ico 8 src/ 9 assets/ 10 components/ 11 utils/ 12 App.js 13 index.css 14 index.js 15 vite.config.js 16 index.html
That's it! Enjoy your speed....
A demo/repos link
No response
Share This Story