Skip to main content

From create-react-app to Vite

· 3 min read
Erik

Over the weekend I finally got the chance to create a React app's initial boilerplate, bundler, and dev server setup using Vite. Previously, I had been using Create React App (CRA) (npx create-react-app) and sometimes using it to deploy to Github pages too.

Vite the Front-end Tool

Vite is a framework-agnostic frontend build tool that was created by the creator of Vue.js. As of now you can use Vite to scaffold not only React apps, but also Vue, Preact, Lit, Svelte, and good ol' vanilla JS! It currently uses Rollup.js as the bundler under the hood, though there seems to be interest to potentially use esbuild once that is mature enough. This differs from CRA which currently uses Webpack.

In this post I'll do a quick comparison on how to start up a React app and deploy it (to Github Pages), with both CRA and Vite. With Vite it's as easy as it is with CRA. Since I mostly use NPM I'll be using the NPM approach, but if you're using Yarn it'll be just as easy, you'll just have to do the equivalent commands.

Vite vs. Create React App

Creating an App

CRA

npx create-react-app my-cool-app

Vite

npm create vite@latest

You'll be prompted with a series of questions to configure it the setup, such as choosing a frontend framework, language (javascript or typescript), and giving the app a name. It's straightforward.

info

npm create - is an alias for npm init, and is equivalent to saying npx create-vite (the actual name of Vite package is create-vite).

Starting a Local Development Server

CRA

npm start
// or
npm run start

Vite

npm run dev

Deploying (to Github Pages)

CRA

As the Github deployment instructions describe, you must add a "homepage" field with your repo URL to your package.json. And then add a "predeploy" and "deploy" scripts.

And finally to deploy run npm run deploy.

Vite

From the Vite deployment instructions, you'll need to add "build" and "preview" in the package.json scripts field if not there.

In vite.config.js add the base value like so:

vite.config.js
/** @type {import('vite').UserConfig} */
export default defineConfig({
// ...
base: "/<YOUR_REPO_NAME>/",
// ..
});

Then in your project root create a shell script named deploy.sh with the contents shown here. And make sure to uncomment one of the git push lines depending on your situation, and update the correct USERNAME and REPO values.

If you're on a Mac you can just run bash deploy.sh and this will build and deploy the static files into gh-pages branch.