Using Vite
What is Vite?
- Vite is a platform that takes your code and turns it into something that the browser can understand.
- It is the build tool and a development server for your TypeScript/JavaScript applications.
- As a development server it has hot module reloading, which greatly speeds up development.
- It replaces existing tools like Webpack and Parcel and is similar to a tools like Snowpack.
- It is context aware to changes, e.g., if you have 1 TS file in your project, it knows to only affect changes on that file, swapped in using WebSockets for extreme speed.
- Vite uses esbuild, which takes your files and compiles them into what you need them to be.
- It uses ESM in your dev flow.
- If you want to do sever side rendering, better to go with something like Svelte or NextJS.
Setting up a Vite project
Here we use pnpm
, but you may use any preferred package manager.
sh
$ pnpm create vite
framework: React
variant: TypeScript + SWC
$ cd <name of project>
$ pnpm install
$ pnpm dev
$ pnpm create vite
framework: React
variant: TypeScript + SWC
$ cd <name of project>
$ pnpm install
$ pnpm dev
Vite with Docker
To enable Vite with Docker, outlined for example in Production-Grade Workflow with Docker, make sure to set the
host
entry totrue
in the vite.config.js file.javascript// https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], server: { host: true, port: 5173 } })
// https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], server: { host: true, port: 5173 } })
Environment Variables
Vite supports environment variables in your client-side code via i
. So as not to leak private variables, only those prefixed with VITE_ will be available in your code. Environment variables are created at build time (this is ubiqutous across client-side applications) so you should never add secrets to VITE environment variables.
The default directory and required prefix can be changed in the vite.config.js file.