DEV Community

Happy
Happy

Posted on

3 Vite Tricks I Wish I Knew When I Started

Ever set up a new Vite project and think "okay, now what?" Here are three small configurations that made my dev experience noticeably better.

1. Path Aliases (No More ../../../)

Deep imports like import { Button } from '../../../components/Button' get messy fast. Vite makes aliases easy.

// vite.config.ts
import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Now you can write:

import { Button } from '@/components/Button';
Enter fullscreen mode Exit fullscreen mode

Much cleaner. If you use TypeScript, also add this to tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What's happening: You're telling Vite "when you see @/, look inside the src/ folder." It's like a shortcut on your desktop — same destination, shorter path.

2. Environment Variables Done Right

Vite only exposes env variables that start with VITE_. This is a security feature — it prevents accidentally leaking server secrets to the browser.

# .env
VITE_API_URL=https://api.example.com
SECRET_KEY=do-not-leak-this
Enter fullscreen mode Exit fullscreen mode
// ✅ This works
console.log(import.meta.env.VITE_API_URL);

// ❌ This is undefined (on purpose!)
console.log(import.meta.env.SECRET_KEY);
Enter fullscreen mode Exit fullscreen mode

Why it matters: In older bundlers like webpack, it was easy to accidentally bundle a secret into your frontend code. Vite's prefix rule makes that harder to do by mistake.

You can also use .env.development and .env.production for different values per environment — Vite picks the right file automatically.

3. Proxy API Requests in Development

CORS errors during development are annoying. Instead of fighting headers, proxy your API calls through Vite's dev server:

// vite.config.ts
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Now when your frontend calls fetch('/api/users'), Vite forwards it to http://localhost:8080/api/users. No CORS issues, no extra configuration.

Think of it like this: Your browser talks to Vite (same origin, no CORS). Vite talks to your backend (server-to-server, no CORS). Problem solved.


These three things — aliases, env variables, and dev proxying — take about five minutes to set up but save hours of frustration. They're the kind of config you do once and forget about.

What's your favourite Vite trick? Drop it in the comments 👇

Happy coding! 🚀

Top comments (0)