As React developers, we're always looking for ways to improve our development experience and application performance. One significant upgrade you might consider is migrating from Create React App (CRA) to Vite. Vite offers faster build times, quicker hot module replacement (HMR), and a more streamlined development experience. In this comprehensive guide, we'll walk through the process of migrating your CRA project to Vite, including handling proxy servers and enabling Gzip compression.
Table of Contents
- Why Migrate to Vite?
- Prerequisites
- Step 1: Create a New Vite Project
- Step 2: Move Your Source Code
- Step 3: Update Package.json
- Step 4: Configure Vite
- Step 5: Update Import Statements
- Step 6: Handle Environment Variables
- Step 7: Update Test Configuration
- Step 8: Configure the Proxy Server
- Step 9: Enable Gzip Compression
- Step 10: Final Cleanup
- Conclusion
Why Migrate to Vite?
Before we dive into the migration process, let's briefly discuss why you might want to switch from CRA to Vite:
- Faster development server startup: Vite uses native ES modules, which significantly reduces the time it takes to start your development server.
- Quicker hot module replacement (HMR): Changes in your code are reflected almost instantly in the browser.
- Improved build performance: Vite's production builds are often faster and result in smaller bundle sizes.
- More flexible configuration: Vite allows for easier customization of your build process.
Prerequisites
Before starting the migration process, ensure you have:
- Node.js (version 18+)
- npm or Yarn
- A Create React App project you want to migrate
Step 1: Create a New Vite Project
First, let's create a new Vite project:
npm create vite@latest my-vite-app -- --template react
cd my-vite-app
This command creates a new Vite project with React template. We'll use this as a base for our migration.
Step 2: Move Your Source Code
Now, let's move your existing source code from the CRA project to the new Vite project:
- Copy the
src
directory from your CRA project to the new Vite project, replacing the existingsrc
directory. - Copy any additional directories you may have (e.g.,
public
,assets
) to the Vite project root.
Step 3: Update Package.json
We need to update the package.json
file to include all the dependencies from your CRA project:
- Copy the
dependencies
anddevDependencies
from your CRA project'spackage.json
to the new Vite project'spackage.json
. - Remove CRA-specific dependencies like
react-scripts
. - Add Vite-specific scripts:
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "vitest",
"lint": "eslint src --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
}
- Install the dependencies:
npm install
Step 4: Configure Vite
Create a vite.config.js
file in the root of your project:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': '/src',
},
},
server: {
port: 3000,
},
})
This configuration sets up the React plugin, defines an alias for the src
directory, and sets the development server port to 3000 (matching CRA's default).
Step 5: Update Import Statements
Vite uses ES modules, so you may need to update some of your import statements:
- Replace
import React from 'react'
withimport * as React from 'react'
in files where you're not using JSX. - Update any imports that use CRA-specific aliases (like
src/
) to use your new alias (@/
) or relative paths.
Step 6: Handle Environment Variables
Vite handles environment variables differently than CRA:
- Rename
.env
files to use the Vite prefix:.env
,.env.local
,.env.development
,.env.production
. - Update environment variable usage in your code:
- Change
process.env.REACT_APP_*
toimport.meta.env.VITE_*
- In your
.env
files, rename variables fromREACT_APP_*
toVITE_*
- Change
Step 7: Update Test Configuration
If you're using Jest with CRA, you'll need to switch to Vitest, which is better integrated with Vite:
- Install Vitest and related packages:
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom
- Create a
vitest.config.js
file in your project root:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/setupTests.js',
},
})
- Update your test files to use Vitest syntax (most Jest tests should work with minimal changes).
Step 8: Configure the Proxy Server
If your CRA project used a proxy configuration, you'll need to set it up in Vite:
- Install
http-proxy
:
npm install -D http-proxy
- Update your
vite.config.js
:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import httpProxy from 'http-proxy'
const proxy = httpProxy.createProxyServer()
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
configure: (proxy, options) => {
proxy.on('error', (err, req, res) => {
console.log('proxy error', err)
})
proxy.on('proxyReq', (proxyReq, req, res) => {
console.log('Sending Request to the Target:', req.method, req.url)
})
proxy.on('proxyRes', (proxyRes, req, res) => {
console.log('Received Response from the Target:', proxyRes.statusCode, req.url)
})
},
},
},
},
})
This configuration sets up a proxy for /api
requests to http://localhost:5000
. Adjust the target URL as needed for your backend.
Step 9: Enable Gzip Compression
To enable Gzip compression in Vite:
- Install the
vite-plugin-compression
plugin:
npm install -D vite-plugin-compression
- Update your
vite.config.js
:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import viteCompression from 'vite-plugin-compression'
export default defineConfig({
plugins: [
react(),
viteCompression({
verbose: true,
disable: false,
threshold: 10240,
algorithm: 'gzip',
ext: '.gz',
}),
],
// ... other configurations
})
This setup will generate Gzip-compressed versions of your assets during the build process.
Step 10: Final Cleanup
-
Remove any CRA-specific files and folders:
- Delete
config-overrides.js
if you were usingreact-app-rewired
- Remove the
eject
script frompackage.json
- Delete
Update your
README.md
to reflect the new Vite setup and commands.Update your CI/CD pipelines to use the new Vite commands (
npm run dev
,npm run build
, etc.).
Conclusion
Migrating from Create React App to Vite can significantly improve your development experience and application performance. While the process involves several steps, the benefits of faster build times, quicker HMR, and more flexible configuration make it a worthwhile endeavor.
Remember to thoroughly test your application after migration to ensure everything works as expected. You may need to make additional adjustments based on your specific project structure and dependencies.
Have you successfully migrated your project from CRA to Vite? Share your experiences and any additional tips in the comments below!
Happy coding!
Top comments (0)