Build Web Apps Absurdly Fast with Vite

reverentgeek

David Neal

Posted on September 13, 2024

Build Web Apps Absurdly Fast with Vite

Let’s face it: the frontend build process has been slow and complicated for too long. Whether you’re dealing with Webpack, Parcel, or your custom Frankenstein monster setup (we’ve all been there), configuring and bundling a web app can be a drag.

Vite is the new kid on the block, ready to blow your mind with speed and simplicity. And Vite isn’t just important for developers; it’s a game-changer for businesses. Speedy development cycles equals happy devs. Happy devs build better code. That means faster time-to-market and lower costs for your business or clients.

Vite is designed to make the pain of slow builds disappear. It takes advantage of native ES modules in the browser, eliminating the need for bundled code on dev builds. Translation: You get hot module replacement (HMR) so fast that your F5 key will feel neglected. Let’s dive into how you can make your projects Vite-powered and never look back.

exclamation point icon

Vite is a French word meaning “quick” or “fast.” It’s pronounced “veet” and rhymes with meet.

Why Vite? Ain’t nobody got time for slow builds

We all know how painful it is to stare at our screen, watching that progress bar crawl along. It’s enough to make you question your life choices.

Vite offers near-instantaneous cold server start, lightning-fast HMR, and builds that are quicker than you can say “npm install.”

  1. Lightning-fast dev startup: Traditional tools like Webpack bundle all your code before serving it. Vite uses native ES modules to serve your code, so it starts fast — the browser loads only what it needs.
  2. Hot Module Replacement: Changes reflect instantly, making your development experience smoother than a jazz saxophone solo.
  3. Out-of-the-box TypeScript support: Vite handles TypeScript without setting up a complicated build pipeline.
  4. Optimized builds: When it’s time to ship, Vite uses Rollup to bundle your code efficiently. It splits your code into chunks, so users aren’t downloading stuff they don’t need.

Get started with Vite

Let’s take Vite for a spin and find out what it can do!

Step 1: Set up your Vite project

First things first, let’s create a new Vite project. Assuming you have Node.js installed, open up your terminal and run:

npm create vite@latest my-awesome-vite-project -- --template react
Enter fullscreen mode Exit fullscreen mode

This command creates a new Vite project with React. Feel free to replace “react” with “vue” or “vanilla” if that’s more your jam. Svelte, Preact, Qwik, and others are supported, too!

Step 2: Install dependencies and run the dev server

Now, let’s install our dependencies and fire up that blazing-fast dev server:

cd my-awesome-vite-project
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

Boom! Your dev server is now running faster than a caffeinated squirrel. Open up your browser. Change one of the source files and marvel at the speed!

Step 3: Structure your project

Vite gives you a pretty bare-bones structure to start with. Here’s a typical setup:

my-awesome-vite-project/
├── public/
│   └── vite.svg
├── src/
│   └── assets/
│       └── react.svg
│   ├── App.css
│   ├── App.jsx
│   ├── index.css
│   └── main.jsx
├── index.html
└── vite.config.js
Enter fullscreen mode Exit fullscreen mode

Feel free to add more folders like styles, utils, or services. Vite won’t judge you.

Step 4: Customize your Vite config

Open up vite.config.js, and let’s add a few settings:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig( {
  plugins: [ react() ],
  server: {
    port: 3000,
  },
  build: {
    outDir: "dist",
    sourcemap: true,
  },
} );
Enter fullscreen mode Exit fullscreen mode

This config sets up your dev server port, output directory for builds, and enables source maps. There are lots more ways to configure Vite to meet your needs!

Step 5: Add some code and watch the magic happen

Let’s create a new component to see Vite’s HMR in action. Create a new file src/Hello.jsx:

import { useState } from "react";

export default function Hello() {
  const [ name, setName ] = useState( "World" );

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <input
        type="text"
        value={name}
        onChange={( e ) => setName( e.target.value )}
        placeholder="Enter a name"
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now, import and use this component in your App.jsx:

import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "../public/vite.svg";
import "./App.css";
import Hello from "./Hello.jsx";

function App() {
  const [ count, setCount ] = useState( 0 );

  return (
    <>
      <Hello />
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount( ( count ) => count + 1 )}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.jsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Save these files and watch as Vite updates your app faster than you can say, “Why didn’t I switch to Vite sooner?”

Neat stuff Vite can do

Vite isn’t a one-trick pony. It’s got some cool features:

  1. Static assets? Got you covered: Vite optimizes your images and other assets automatically.
  2. Environment variables? Yep: Use .env files to manage different environments easily.
  3. Plugins? Tons of ’em: Need more features? There’s probably a plugin for that.
  4. CSS pre-processors? Sure thing: Want to use Sass? Just install it and start using it. Vite figures out the rest.

Example of adding Sass to Vite

npm install --save-dev sass
Enter fullscreen mode Exit fullscreen mode

Create a file named App.scss in the src folder and add some code, such as:

$awesome-color: #ff69b4;
.card {
    color: $awesome-color;
}
Enter fullscreen mode Exit fullscreen mode

Update App.jsx to import the new Sass file:

import './App.scss';
Enter fullscreen mode Exit fullscreen mode

Wrapping up: Vite is sweet!

  1. Speed matters – Vite’s dev server is so fast you’ll forget you ever had to refresh a page.
  2. Easy setup – With one simple command, you can spin up a project, ready to go.
  3. Framework agnostic – Whether you’re into React, Vue, Svelte, Preact, Solid, Qwik, or you prefer the taste of plain vanilla JavaScript, Vite has your back.
  4. Production ready – Rollup optimization ensures your code is as lean and fast as possible.

Now, go forth and build something awesome! Vite it!

David Neal

About Me

Hi, I’m David! I’ve been a web developer pretty much since the beginning of the “World Wide Web”. My mission is to help folks in technology be more awesome! I also do all my own stunts… I mean… illustrations and graphics. You can learn more about me over on my website ReverentGeek.com.

💖 💪 🙅 🚩
reverentgeek
David Neal

Posted on September 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related