Why Vite and how to migrate a existing React Aplication
This article and guide is aimed at people who want to improve their productivity in development environments and give strong reasons why replacing Webpack with another Module Bundle is a very good idea.
To put us in context, if you are starting to use react or have already been using react as a base for some time, I will tell you about my experience with webpack and my conclusions from it.
Webpack came and simplified our lives in many aspects and frontend productivity changed and improved in many ways.
Webpack is and will continue to be for some time the most used Module Bundle, my conclusion is because the community in general is not very aware of the new bets and benefits that the most modern Module Bundles give us and of those the one that is most highlighting is Vite. I won’t go into technical details about vite, but I will tell you about my experience with both.
As we can see, our focus is not on React, since if you are reading this article it is probably your favorite library at the moment.
Currently I do not use React Create, instead I use Next.js which is an impressive framework and has a lot of harmony with React in which you can apply SSR CSR in a much easier way, since it was designed with that in mind, when creating an Application in React from scratch, Next.js is one of the most promising alternatives, but
Given that Next has several differences when managing certain technical issues and a different logic, which makes a migration from a React application to Next not sound so tempting, Vite enters right in this section, but before talking about Vite, I will tell you the reasons which is why creating a React app without some framework is not such a good idea.
As we know, when working with React, we have to use a Module Bundle to adapt our code to the browser, in this case React offers us the base Webpack, I will not go into details about Webpack, but the reason for mentioning it is that this Module Bundle does everything the magic to be able to see our application and that it works correctly in the browser.
Every time we add code and we want to reflect the changes, since WebPack today has many processes behind it, the compilation is its Achilles heel and can become a headache, I could find myself in situations in which I found myself with the obligation to wait 3 minutes to see changes in large Applications, that increases the more your Application grows, obviously there are many alternatives to be able to improve those compilation times and thus be able to improve our productivity when developing, but why not start with one base quite oriented to improve the development experience ?, this is where Vite comes in.
Vite came with many things in mind and the bottom line is to eliminate Webpack’s weaknesses and improve developer productivity. When trying vite I could see that the changes are very big compared to the traditional, and my development experience increased drastically, this is thanks to the fact that Vite uses Esbuild for its Pre-bundle adding the way Vite handles the compilation, In short, Vite simplifies drastically the entire compilation process.
Here a simple Example about Esbuild
Here I show you a small comparison of React in webpack and Vite in a small application
as we can see with vite it takes us only about 80 seconds to compile our entire application that translates to 1.30 seconds, maybe you won’t see it tempting until you see how long it takes with Webpack, as you can see, we need to optimize some imports and complete well the migration and whether to improve the compilation times even more
On the other hand, with webpack, the compilation time took 310 seconds, which is equivalent to 5.1 minutes, the difference in this case is abysmal and Vite comes out totally victorious.
The nicest thing about Vite is that you can reflect your code changes without losing app state and in a matter of seconds since it handles the build differently. webpack can take many minutes.
That said, and if you want to try Vite and improve your productivity, I will guide you so you can migrate your React Application to Vite and take advantage of this Module Bundle that has been gaining a lot of ground over Webpack.
Before starting we must take into account that both Webpack 5 and Vite do not support poly-fill Node.js built-in modules for the browser at first, that means that for both webpack5 and Vite, some configurations have to be done additional.
I currently work with TypeScript which makes the settings slightly different.
Here We Go!!!
1. Update Package.json
We will modify the scripts of our package.json to adapt them to Vite
"scripts": {
"start": "vite",
"build": "tsc && vite build",
"serve": "vite preview",
},
!Let’s make sure we remove react-scripts from our dependencies , we won’t need it anymore
Let’s add our new dependencies
"@vitejs/plugin-react-refresh": "^1.3.1",
"vite-plugin-svgr" :"^0.3.0",
"vite": "^2.9.12"
You can also install it directly in the best case
yarn add vite @vitejs/plugin-react-refresh vite-plugin-svgr
//or
// npm i vite @vitejs/plugin-react-refresh vite-plugin-svgr
2. Add Vite Config File
Add `vite.config.ts` to the root of your project. We will only use the basic configuration, you can see the configurations in more detail in their own documentations
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import svgrPlugin from 'vite-plugin-svgr'
// see all documentation here https://vitejs.dev/config/
export default defineConfig({
// This changes the out put dir from dist to build change as your need
// comment this out if that isn't relevant for your project
build: {
outDir: 'build',
},
plugins: [
reactRefresh(),
svgrPlugin({
svgrOptions: {
icon: true,
// ...svgr options (https://react-svgr.com/docs/options/)
},
}),
],
})
3. Update your tsconfig.json
At the moment I am using this configuration, I am still improving it but it meets the requirements at the moment, in case you want to adapt it and improve it to your needs you can consult the documentation.
You must configure tsconfig.json to use esnext as the target, lib, and module type.
{
"compilerOptions": {
"target": "ESNext",
"lib": ["dom", "dom.iterable", "esnext"],
"types": ["vite/client", "vite-plugin-svgr/client"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
4. Install New Dependencies
Run yarn
or npm i
to install all the new dependencies we have added to the project.
5. Move your index.html file
Move the index.html from /public
out to the root of the project.
Vite doesn’t need the index.html to be in the public folder any more.
5. Update the content of index.html
Vite handles urls in the index.html differently to create react app.
Remove any %PUBLIC_URL%
references from the file. Just replace that string with ""
.
It’s a small change so don’t be scared
<!-- This is the create react app url. change this to not have the variable... -->
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<!-- Replace -->
<!-- ... Should be like This -->
<link rel="icon" href="/favicon.ico" />
Add a script tag with the project entrypoint, Vite needs it to get your Entry React Component.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- Like below. This is the script tag for bootstrapping your Vite application -->
<script type="module" src="/src/index.tsx"></script>
</body>
7. Update all your env vars if you use them
Rename your environment variables so they start with VITE_
e.g. search and replace REACT_APP_
toVITE_
# this create react app variable
REACT_APP_MY_VAR
# should be this in Vite
VITE_MY_VAR
Vite uses the ECMAScript module import.meta properties to pass environment variables to the modules.
To access these environment variables you must change all process.env.
s to import.meta.env.
!I know it can be annoying if you already have many variables and changing them all can be a nightmare, here I have a solution!
The plugin will load VUE_APP_
or REACT_APP_
environment variables to process.env. You might need this if you are using a library that expects an env var to be on process.env for example.
yarn add vite-plugin-env-compatible
//or//
npm i vite-plugin-env-compatible
and add
envCompatible(/* options */)
to your vite.config.ts plugins section.
In Case You Use SaSS
I tell you that I use Styled Components for the styles, it offers me a solution to have more modular components and thus be able to reuse components faster, I recommend that you review it,
But maybe you are using Sass or some Library is using it, I highly recommend using TailWind or StyledComponentes,
In case it is Sass, you have to install a preprocessor
yarn add -D sass
//or//
npm i --save-dev sass
Possible Incompatibilities with the AWS SDK
Currently I use AWS services a lot since my applications run on Amplify and I use the user verification that amplify offers, I could see that there are certain incompatibilities and it has already been discussed enough, sip it, I was able to solve it but that would make this guide even more extensive , I will leave it for an additional guide for this problem, I will leave you a discussion thread for the moment Here.
support poly-fill Node.js built-in modules
I am evaluating if it is feasible to create an article to cover this section for both Webpack5 and Vite, I could appreciate that there are good articles available, in case I can add something else I will do it.
In this article I was referring to vite as a module bundle but it is much more powerful than that, you can touch many more aspects of an application and for this very reason I recommend you to carefully review the documentation, that being said, I hope you enjoy playing with Vite for a while good time.
This is my small grain of sand to help migrate to this incredible Module Bundle that has a great future.
Any correction or suggestion to improve this guide, do not hesitate to do it.