> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/withastro/astro/llms.txt
> Use this file to discover all available pages before exploring further.

# Vite Configuration

> Configure Vite in your Astro project for advanced customization and optimization

Astro is built on top of [Vite](https://vite.dev), a fast and modern build tool. You can pass additional Vite configuration options through the `vite` key in your Astro config.

## Basic Vite Configuration

Add Vite configuration to your `astro.config.mjs`:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    // Vite configuration options here
  }
});
```

<Note>
  Astro automatically configures Vite with sensible defaults. Only add custom Vite config when you need to override or extend the defaults.
</Note>

## Common Use Cases

### Adding Vite Plugins

Extend Vite with community plugins:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  vite: {
    plugins: [tailwindcss()]
  }
});
```

<Tip>
  Many popular tools have Astro integrations that handle Vite configuration for you. Check the [integrations directory](https://astro.build/integrations/) first.
</Tip>

### Configuring SSR External Packages

Exclude problematic packages from SSR processing:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    ssr: {
      external: ['broken-npm-package']
    }
  }
});
```

<Accordion title="When to use ssr.external">
  Use this when a package:

  * Has CommonJS modules that break during SSR
  * Uses Node.js built-ins that need to be excluded
  * Has incompatible dependencies
  * Causes "Cannot use import statement outside a module" errors
</Accordion>

### Adding Module Aliases

Create import aliases (TypeScript users should also update `tsconfig.json`):

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';
import path from 'path';

export default defineConfig({
  vite: {
    resolve: {
      alias: {
        '@components': path.resolve('./src/components'),
        '@lib': path.resolve('./src/lib')
      }
    }
  }
});
```

Then use in your code:

```astro title="src/pages/index.astro" theme={null}
---
import Card from '@components/Card.astro';
import { formatDate } from '@lib/utils';
---
```

<Note>
  Astro provides `@/*` as an alias to `src/*` by default. For TypeScript projects, also configure path mappings in `tsconfig.json`.
</Note>

### Environment Variables

Customize which environment variables are exposed to your client-side code:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    define: {
      'import.meta.env.CUSTOM_VAR': JSON.stringify(process.env.CUSTOM_VAR)
    }
  }
});
```

<Warning>
  Only use `define` for non-secret values. Secrets should never be exposed to client code.
</Warning>

### Optimizing Dependencies

Control which dependencies Vite pre-bundles:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    optimizeDeps: {
      include: ['linked-package'],
      exclude: ['heavy-package']
    }
  }
});
```

<Accordion title="When to optimize dependencies">
  **Include** when:

  * A package is linked locally and not being detected
  * A package has many internal modules that slow down dev server
  * You're experiencing slow initial page loads

  **Exclude** when:

  * A package is very large and slows down the dev server startup
  * A package has conditional imports that break when pre-bundled
</Accordion>

## Advanced Configuration

### Build Options

Customize the build output:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'vendor': ['react', 'react-dom']
          }
        }
      },
      cssMinify: 'lightningcss',
      minify: 'terser'
    }
  }
});
```

<Info>
  Vite uses [Rollup](https://rollupjs.org/) for production builds. Use `rollupOptions` to configure Rollup directly.
</Info>

### CSS Configuration

Configure CSS processing:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "src/styles/variables.scss";`
        }
      }
    }
  }
});
```

### Server Options

Configure the Vite dev server:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    server: {
      fs: {
        allow: ['..']  // Allow serving files from parent directory
      },
      watch: {
        usePolling: true  // Use polling for file watching (useful in Docker)
      }
    }
  }
});
```

<Accordion title="Common server options">
  * **`server.fs.allow`**: Restrict file system access for security
  * **`server.watch.usePolling`**: Enable polling for file watching (Docker, WSL)
  * **`server.proxy`**: Configure proxy for API requests
  * **`server.cors`**: Enable CORS for development
</Accordion>

### Proxy Configuration

Proxy API requests during development:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    server: {
      proxy: {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  }
});
```

Now requests to `/api/users` are proxied to `http://localhost:3000/users`.

## Framework-Specific Configuration

### React

Customize React plugin options:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';

export default defineConfig({
  integrations: [react()],
  vite: {
    esbuild: {
      jsxInject: `import React from 'react'`
    }
  }
});
```

### Vue

Configure Vue plugin:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';
import vue from '@astrojs/vue';

export default defineConfig({
  integrations: [vue()],
  vite: {
    vue: {
      template: {
        compilerOptions: {
          isCustomElement: (tag) => tag.startsWith('ion-')
        }
      }
    }
  }
});
```

## Performance Optimization

### Code Splitting

Optimize bundle size with manual chunks:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('react')) {
                return 'vendor-react';
              }
              return 'vendor';
            }
          }
        }
      }
    }
  }
});
```

<CardGroup cols={2}>
  <Card title="Benefits" icon="rocket">
    * Smaller initial bundle
    * Better caching
    * Parallel downloads
  </Card>

  <Card title="Trade-offs" icon="scale-balanced">
    * More HTTP requests
    * Complex configuration
    * Overhead for small sites
  </Card>
</CardGroup>

### Asset Optimization

Configure asset handling:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    build: {
      assetsInlineLimit: 4096,  // 4kb
      cssCodeSplit: true
    }
  }
});
```

* **`assetsInlineLimit`**: Assets smaller than this are inlined as base64
* **`cssCodeSplit`**: Enable CSS code splitting

## Environment-Specific Configuration

Configure Vite differently for dev vs. build:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig(({ command, mode }) => {
  const isDev = command === 'dev';
  
  return {
    vite: {
      logLevel: isDev ? 'info' : 'warn',
      build: {
        sourcemap: isDev,
        minify: !isDev
      }
    }
  };
});
```

<Info>
  The config function receives `command` ("dev" | "build" | "preview") and `mode` ("development" | "production").
</Info>

## Debugging Vite

### Enable Debug Logging

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    logLevel: 'info',  // 'error' | 'warn' | 'info' | 'silent'
    clearScreen: false
  }
});
```

### Inspect Bundle

Use the [rollup-plugin-visualizer](https://github.com/btd/rollup-plugin-visualizer) to analyze your bundle:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  vite: {
    plugins: [
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true
      })
    ]
  }
});
```

Run `astro build` to generate a visual report of your bundle.

## Common Issues

<AccordionGroup>
  <Accordion title="Module not found errors">
    Try adding the module to `vite.optimizeDeps.include`:

    ```js title="astro.config.mjs" theme={null}
    export default defineConfig({
      vite: {
        optimizeDeps: {
          include: ['problematic-package']
        }
      }
    });
    ```
  </Accordion>

  <Accordion title="Slow dev server startup">
    Exclude large dependencies from optimization:

    ```js title="astro.config.mjs" theme={null}
    export default defineConfig({
      vite: {
        optimizeDeps: {
          exclude: ['large-package']
        }
      }
    });
    ```
  </Accordion>

  <Accordion title="SSR errors with CommonJS packages">
    Mark the package as external:

    ```js title="astro.config.mjs" theme={null}
    export default defineConfig({
      vite: {
        ssr: {
          external: ['cjs-package']
        }
      }
    });
    ```
  </Accordion>

  <Accordion title="File watching not working (Docker/WSL)">
    Enable polling:

    ```js title="astro.config.mjs" theme={null}
    export default defineConfig({
      vite: {
        server: {
          watch: {
            usePolling: true
          }
        }
      }
    });
    ```
  </Accordion>
</AccordionGroup>

## Complete Example

Here's a comprehensive Vite configuration example:

```js title="astro.config.mjs" theme={null}
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
import path from 'path';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  integrations: [react()],
  vite: {
    // Plugins
    plugins: [tailwindcss()],
    
    // Aliases
    resolve: {
      alias: {
        '@components': path.resolve('./src/components'),
        '@lib': path.resolve('./src/lib')
      }
    },
    
    // SSR Configuration
    ssr: {
      external: ['@prisma/client']
    },
    
    // Dependency Optimization
    optimizeDeps: {
      include: ['linked-package'],
      exclude: ['heavy-package']
    },
    
    // Build Options
    build: {
      sourcemap: true,
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['react', 'react-dom']
          }
        }
      }
    },
    
    // CSS Options
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "src/styles/variables.scss";`
        }
      }
    },
    
    // Server Options
    server: {
      proxy: {
        '/api': 'http://localhost:3000'
      },
      watch: {
        usePolling: process.env.USE_POLLING === 'true'
      }
    }
  }
});
```

## Learn More

<CardGroup cols={2}>
  <Card title="Vite Documentation" icon="external-link" href="https://vite.dev/config/">
    Official Vite configuration reference
  </Card>

  <Card title="Astro Config" icon="gear" href="/config/astro-config">
    Complete Astro configuration reference
  </Card>

  <Card title="Integrations" icon="puzzle-piece" href="/integrations/overview">
    Learn about Astro integrations
  </Card>

  <Card title="Build Options" icon="hammer" href="/config/astro-config">
    Astro build configuration
  </Card>
</CardGroup>
