Overview
How to configure Vue 3 with Vite
Modern Vue 3 applications rely exclusively on Vite as their build tool. The vite.config.ts file dictates how your Vue SFCs (Single File Components) are compiled, how your local dev server handles CORS, and how your production assets are bundled.
Best Practices
- Path Aliasing (@/): Using relative paths like `../../../../components/Button.vue` is a nightmare for refactoring. Configuring a path alias in Vite (e.g., `@:./src`) allows you to import cleanly: `import Button from '@/components/Button.vue'`. Remember, you MUST also sync this alias in your `tsconfig.json` so the TypeScript compiler doesn't throw errors.
- The Development API Proxy: During local development, your Vue app (running on port 5173) cannot easily make requests to your backend (running on port 8080) due to CORS restrictions. The Vite API Proxy solves this by capturing requests to `/api` and silently forwarding them to your backend, bypassing the browser's CORS policy entirely.
Security Recommendations
- Production Source Maps: If you enable sourcemaps in production, anyone can open their browser's DevTools and read your original, uncompiled Vue source code. While useful for debugging services like Sentry, you should generally disable them or ensure your web server blocks public access to `.map` files.
Frequently Asked Questions
Why do I need the @vitejs/plugin-vue plugin?
Vite does not understand Vue Single File Components (.vue) out of the box. The official Vue plugin compiles the template, script, and style blocks into standard JavaScript and CSS during the build process.
What is library mode?
If you are building a UI component library (e.g., an internal design system) meant to be published to NPM, you use Library Mode. This tells Vite to export your components as an ES Module, and externalizes 'vue' so the consuming application doesn't bundle Vue twice.
How do I expose environment variables in Vue?
Vite requires environment variables to start with `VITE_` (or your custom `envPrefix`) to be accessible in your Vue components via `import.meta.env`. Any variable without this prefix is strictly stripped from the client build for security. NEVER prefix a private database or API key.