Converting create-react-app to Vite
https://semaphoreci.com/blog/vite
- Remove the
react-scripts
dependency from the package.json. - Add
sass
in package.json, if you are using CSS or SCSS.
yarn add -D sass //or npm i --save-dev sass
3. Add vite
and @vitejs/plugin-react
as dev dependencies.
"devDependencies": { "@vitejs/plugin-react": "1.3.2", "vite": "2.7.0" }
4. Replace the start
and build
scripts as below:
"scripts": { "start": "vite", "build": "vite build" },
5. Create a file vite.config.js
in the root of the project with the below code:
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default () => { return defineConfig({ plugins: [react()], }) }
6. Move the index.html file from the public folder to the root of the project.
7. Remove all the occurrences of %PUBLIC_URL%
from index.html.
The lines affected should look like the following lines after the change:
<link rel="icon" href="/favicon.ico" /> <link rel="manifest" href="/manifest.json" /> <link rel="apple-touch-icon" href="/logo192.png" />
8. Add the script tag below into the body of index.html:
<script type="module" src="/src/index.jsx"></script>
NOTE: In CRA, src/index
has extension of .js
, change it to jsx
.
9. Change the extension of .js
files to .jsx
, if they contain jsx syntax.
If not changed, you will get the following error:
[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
10. Update all environment variables from REACT_APP
to VITE
.
Replace REACT_APP_HOST_URL
to VITE_HOST_URL
11. Vite does not support absolute path by default.
You need to either use a relative path or add an alias.
import App from "components/search/App"; // Not supported import App from '../src/components/search/App'; // Use relative path
You can add an alias in vite.config.js as below:
export default () => { return defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, './src'), }, }, }); }
Now, you can use the next line:
import App from '@/components/search/App'
Finally installing dependencies using:
yarn install or npm install
12. Start your application with, as shown below:
yarn start or npm start
Vite also doesn't seem to like process.env, or process at all. It uses import.meta.env instead.