Skip to main content

Vite & Vitest example

In this guide, you'll learn how to integrate Vite and Vitest into moon.

Begin by creating a new Vite project in the root of an existing moon project (this should not be created in the workspace root, unless a polyrepo).

yarn create vite

If you plan on using Vitest, run the following command to add the vitest dependency to a project, otherwise skip to the setup section.

yarn workspace <project> add --dev vitest

Setup

Since Vite is per-project, the associated moon tasks should be defined in each project's moon.yml file.

<project>/moon.yml
fileGroups:
vite:
- 'src/**/*'
- 'env.d.ts'
- 'index.html'
- 'vite.config.*'

tasks:
# Development server
dev:
command: 'vite dev'
local: true

# Production build
build:
command: 'vite build'
inputs:
- '@group(vite)'
outputs:
- 'dist'

# Preview production build locally
preview:
command: 'vite preview'
deps:
- '~:build'
local: true

# Unit testing (if using Vitest)
test:
command:
- 'vitest'
- 'run'
# Always run code coverage
- '--coverage'
# Dont fail if a project has no tests
- '--passWithNoTests'
inputs:
- '@group(vite)'
- 'tests/**/*'
- 'vitest.config.*'

Configuration

Root-level

We suggest against root-level configuration, as Vite should be installed per-project, and the vite command expects the configuration to live relative to the project root.

Project-level

When creating a new Vite project, a vite.config.<js|ts> is created, and must exist in the project root.

<project>/vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
// ...
build: {
// These must be `outputs` in the `build` task
outDir: 'dist',
},
test: {
// Vitest settings
},
});

If you'd prefer to configure Vitest in a separate configuration file, create a vitest.config.<js|ts> file.