|
======================== |
|
CODE SNIPPETS |
|
======================== |
|
TITLE: Create and Start Vite Dev Server |
|
DESCRIPTION: Demonstrates how to programmatically create a Vite development server instance using `createServer` and start it with `listen`. It also shows how to print server URLs. |
|
|
|
SOURCE: https://vite.dev/index |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { createServer } from 'vite' |
|
|
|
const server = await createServer({ |
|
// user config options |
|
}) |
|
await server.listen() |
|
server.printUrls() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install and Deploy with Netlify CLI |
|
DESCRIPTION: Commands to install the Netlify CLI globally, initialize a new Netlify site, and deploy the project. The `--prod` flag is used for production deployments. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
# Install the Netlify CLI |
|
$ npm install -g netlify-cli |
|
|
|
# Create a new site in Netlify |
|
$ ntl init |
|
|
|
# Deploy to a unique preview URL |
|
$ ntl deploy |
|
|
|
# Deploy the site into production |
|
$ ntl deploy --prod |
|
|
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Framework-Specific Vite Starters |
|
DESCRIPTION: Direct commands to create starter projects for popular frameworks, leveraging Vite. These provide optimized setups for specific ecosystems. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite6 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
create-vue |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npx nuxi init |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm create svelte@latest my-app |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npx create-remix@latest |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npx create-analog@latest |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
ng new my-app --style=scss --standalone=false |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Lightning CSS Setup |
|
DESCRIPTION: Explains how to enable experimental support for Lightning CSS as a CSS transformer and minifier in Vite. This requires installing the `lightningcss` package and configuring Vite's build options. |
|
|
|
SOURCE: https://vite.dev/guide/features |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm add -D lightningcss |
|
``` |
|
|
|
LANGUAGE: json |
|
CODE: |
|
``` |
|
// vite.config.js |
|
// For transformer: |
|
export default { |
|
css: { |
|
transformer: 'lightningcss' |
|
} |
|
} |
|
|
|
// For minifier: |
|
export default { |
|
build: { |
|
cssMinify: 'lightningcss' |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Build and Link Vite from Source |
|
DESCRIPTION: Steps to clone the Vite repository, build it locally, and link it globally for development. Requires pnpm for installation and linking. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
git clone https://github.com/vitejs/vite.git |
|
cd vite |
|
pnpm install |
|
cd packages/vite |
|
pnpm run build |
|
pnpm link --global # use your preferred package manager for this step |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server Environment Setup |
|
DESCRIPTION: Example of setting up Vite server environments, specifically configuring a worker environment. This involves creating a custom environment factory that manages communication with a worker process. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-runtimes |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { BroadcastChannel } from 'node:worker_threads' |
|
import { createServer, RemoteEnvironmentTransport, DevEnvironment } from 'vite' |
|
|
|
function createWorkerEnvironment(name, config, context) { |
|
const worker = new Worker('./worker.js') |
|
const handlerToWorkerListener = new WeakMap() |
|
|
|
const workerHotChannel = { |
|
send: (data) => worker.postMessage(data), |
|
on: (event, handler) => { |
|
if (event === 'connection') return |
|
|
|
const listener = (value) => { |
|
if (value.type === 'custom' && value.event === event) { |
|
const client = { |
|
send(payload) { |
|
worker.postMessage(payload) |
|
}, |
|
} |
|
handler(value.data, client) |
|
} |
|
} |
|
handlerToWorkerListener.set(handler, listener) |
|
worker.on('message', listener) |
|
}, |
|
off: (event, handler) => { |
|
if (event === 'connection') return |
|
const listener = handlerToWorkerListener.get(handler) |
|
if (listener) { |
|
worker.off('message', listener) |
|
handlerToWorkerListener.delete(handler) |
|
} |
|
}, |
|
} |
|
|
|
return new DevEnvironment(name, config, { |
|
transport: workerHotChannel, |
|
}) |
|
} |
|
|
|
await createServer({ |
|
environments: { |
|
worker: { |
|
dev: { |
|
createEnvironment: createWorkerEnvironment, |
|
}, |
|
}, |
|
}, |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Preview Configuration Example |
|
DESCRIPTION: Example of how to configure Vite's preview server options within the vite.config.js file. This demonstrates setting custom ports for both the development server and the preview server. |
|
|
|
SOURCE: https://vite.dev/config/preview-options |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
export default defineConfig({ |
|
server: { |
|
port: 3030, |
|
}, |
|
preview: { |
|
port: 8080, |
|
}, |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Preview Vite Build Output |
|
DESCRIPTION: To resolve CORS errors when opening built HTML files directly via the 'file' protocol, serve the build output using a local HTTP server. The `vite preview` command starts a local server for previewing your production build. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npx vite preview |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: ModuleRunner Example Usage |
|
DESCRIPTION: Demonstrates how to instantiate and use the ModuleRunner with an ESModulesEvaluator and a transport implementation. It shows the basic setup for importing a module. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-runtimes |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner' |
|
import { transport } from './rpc-implementation.js' |
|
|
|
const moduleRunner = new ModuleRunner( |
|
{ |
|
transport, |
|
}, |
|
new ESModulesEvaluator(), |
|
) |
|
|
|
await moduleRunner.import('/src/entry-point.js') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Vite App |
|
DESCRIPTION: Scaffolds a new Vite project with your preferred framework. Use this command to quickly start a new Vite-based application. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite6 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm create vite |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Vite from Unreleased Commits |
|
DESCRIPTION: Installs a specific commit of Vite from the pkg.pr.new service, allowing testing of unreleased features. Requires replacing 'SHA' with a valid commit hash. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npm install -D https://pkg.pr.new/vite@SHA |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ yarn add -D https://pkg.pr.new/vite@SHA |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pnpm add -D https://pkg.pr.new/vite@SHA |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ bun add -D https://pkg.pr.new/vite@SHA |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Playground with vite.new |
|
DESCRIPTION: Access Vite 4 playgrounds online by visiting vite.new. This is useful for quickly testing Vite with different frameworks without local setup. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite4 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
vite.new |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Vite Development Server |
|
DESCRIPTION: Commands to start the Vite development server using different package managers. The server serves the index.html file and hot-reloads changes. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npx vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ yarn vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pnpm vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ bunx vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ deno run -A npm:vite |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server Warmup Configuration |
|
DESCRIPTION: Configuration example for Vite's `server.warmup` option in `vite.config.js`. This pre-transforms and caches specified client files to improve startup performance and reduce request waterfalls. |
|
|
|
SOURCE: https://vite.dev/guide/performance |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { defineConfig } from 'vite'; |
|
|
|
export default defineConfig({ |
|
server: { |
|
warmup: { |
|
clientFiles: [ |
|
'./src/components/BigComponent.vue', |
|
'./src/utils/big-utils.js', |
|
], |
|
}, |
|
}, |
|
}); |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Scaffold Vite Project (with Template) |
|
DESCRIPTION: Commands to create a new Vite project and specify a framework template directly. This allows for immediate setup of projects like Vite + Vue or Vite + React. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
# npm 7+, extra double-dash is needed: |
|
$ npm create vite@latest my-vue-app -- --template vue |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ yarn create vite my-vue-app --template vue |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pnpm create vite my-vue-app --template vue |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ bun create vite my-vue-app --template vue |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ deno init --npm vite my-vue-app --template vue |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Deploy to xmit |
|
DESCRIPTION: Deploy your static site using xmit Static Site Hosting by following their specific guide for Vite projects. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# Follow xmit's Vite quickstart guide for deployment steps. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example Library Entry File |
|
DESCRIPTION: This JavaScript file serves as an entry point for a library. It imports components or modules (e.g., Foo.vue, Bar.vue) and exports them, making them available for users who import the library package. |
|
|
|
SOURCE: https://vite.dev/guide/build |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import Foo from './Foo.vue' |
|
import Bar from './Bar.vue' |
|
export { Foo, Bar } |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Dev Server Commands |
|
DESCRIPTION: Commands and options for starting the Vite development server. This includes specifying the root directory, host, port, and other server behaviors. |
|
|
|
SOURCE: https://vite.dev/guide/cli |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
vite dev [root] |
|
vite serve [root] |
|
|
|
Starts Vite dev server in the current directory. `vite dev` and `vite serve` are aliases. |
|
|
|
Parameters: |
|
root: The root directory of the project (optional). |
|
|
|
Options: |
|
--host [host] |
|
Specify hostname (string). Example: --host 0.0.0.0 |
|
--port <port> |
|
Specify port (number). Example: --port 3000 |
|
--open [path] |
|
Open browser on startup (boolean | string). Example: --open |
|
Example: --open /about |
|
--cors |
|
Enable CORS (boolean). |
|
--strictPort |
|
Exit if specified port is already in use (boolean). |
|
--force |
|
Force the optimizer to ignore the cache and re-bundle (boolean). |
|
-c, --config <file> |
|
Use specified config file (string). Example: -c vite.config.ts |
|
--base <path> |
|
Public base path (default: '/'). Example: --base /app/ |
|
-l, --logLevel <level> |
|
Set log level (info | warn | error | silent). Example: -l warn |
|
--clearScreen |
|
Allow/disable clear screen when logging (boolean). |
|
--configLoader <loader> |
|
Use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: 'bundle'). Example: --configLoader runner |
|
--profile |
|
Start built-in Node.js inspector (check [Performance bottlenecks](/guide/troubleshooting#performance-bottlenecks)). |
|
-d, --debug [feat] |
|
Show debug logs (string | boolean). Example: -d optimize |
|
Example: -d true |
|
-f, --filter <filter> |
|
Filter debug logs (string). Example: -f plugin-name |
|
-m, --mode <mode> |
|
Set env mode (string). Example: -m production |
|
-h, --help |
|
Display available CLI options. |
|
-v, --version |
|
Display version number. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Vite Preview Locally |
|
DESCRIPTION: Starts a local static web server to preview the production build. This command serves files from the `dist` directory, allowing you to test the application's appearance and functionality in a production-like environment. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npm run preview |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite CSS Pre-processor Installation |
|
DESCRIPTION: Provides the necessary npm commands to install supported CSS pre-processors for use with Vite. Vite includes built-in support for Sass, Less, and Stylus. |
|
|
|
SOURCE: https://vite.dev/guide/features |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
# .scss and .sass |
|
npm add -D sass-embedded # or sass |
|
|
|
# .less |
|
npm add -D less |
|
|
|
# .styl and .stylus |
|
npm add -D stylus |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Improve Server Cold Starts |
|
DESCRIPTION: Switch to a new strategy for dependency optimization that may help in large projects by holding off optimization until crawling is complete. This can be beneficial for projects experiencing slow server cold starts. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite5-1 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
vite.config.js |
|
|
|
export default { |
|
optimizeDeps: { |
|
holdUntilCrawlEnd: false |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vercel CLI Deployment |
|
DESCRIPTION: Installs the Vercel CLI, initializes a Vite project, and provides commands to deploy the application. Vercel automatically detects Vite and configures settings. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npm i -g vercel |
|
$ vercel init vite |
|
Vercel CLI |
|
> Success! Initialized "vite" example in ~/your-folder. |
|
- To deploy, `cd vite` and run `vercel`. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Vite CLI with Package Managers |
|
DESCRIPTION: Installs the Vite CLI as a development dependency using different package managers like npm, yarn, pnpm, bun, and deno. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npm install -D vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ yarn add -D vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pnpm add -D vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ bun add -D vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ deno add -D npm:vite |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Custom Logger Example (TypeScript) |
|
DESCRIPTION: Demonstrates how to create and customize a Vite logger. This example shows how to use `createLogger` to get the default logger and then override its `warn` method to filter out specific warnings, such as empty CSS files. |
|
|
|
SOURCE: https://vite.dev/config/shared-options |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import { |
|
createLogger, |
|
defineConfig |
|
} from 'vite' |
|
|
|
const logger = createLogger() |
|
const loggerWarn = logger.warn |
|
logger.warn = (msg, options) => { |
|
// Ignore empty CSS files warning |
|
if (msg.includes('vite:css') && msg.includes(' is empty')) return |
|
loggerWarn(msg, options) |
|
} |
|
|
|
export default defineConfig({ |
|
customLogger: logger, |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Default npm Scripts |
|
DESCRIPTION: Defines the standard npm scripts for common Vite operations: starting the dev server, building for production, and previewing the production build. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: json |
|
CODE: |
|
``` |
|
{ |
|
"scripts": { |
|
"dev": "vite", // start dev server, aliases: `vite dev`, `vite serve` |
|
"build": "vite build", // build for production |
|
"preview": "vite preview" // locally preview production build |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server Middleware Mode Example |
|
DESCRIPTION: Demonstrates how to create a Vite development server in middleware mode, integrating it with an Express.js application. This allows Vite to handle requests within a custom server setup. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import express from 'express' |
|
import { createServer as createViteServer } from 'vite' |
|
|
|
async function createServer() { |
|
const app = express() |
|
|
|
// Create Vite server in middleware mode |
|
const vite = await createViteServer({ |
|
server: { |
|
middlewareMode: true |
|
}, |
|
// don't include Vite's default HTML handling middlewares |
|
appType: 'custom' |
|
}) |
|
// Use vite's connect instance as middleware |
|
app.use(vite.middlewares) |
|
|
|
app.use('*', async (req, res) => { |
|
// Since `appType` is `'custom'`, should serve response here. |
|
// Note: if `appType` is `'spa'` or `'mpa'`, Vite includes middlewares |
|
// to handle HTML requests and 404s so user middlewares should be added |
|
// before Vite's middlewares to take effect instead |
|
}) |
|
} |
|
|
|
createServer() |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Custom Environment Instance Configuration |
|
DESCRIPTION: Example of configuring a custom 'ssr' environment using a provider, specifying a distinct output directory for the build process. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { customEnvironment } from 'vite-environment-provider' |
|
|
|
export default { |
|
build: { |
|
outDir: '/dist/client', |
|
}, |
|
environments: { |
|
ssr: customEnvironment({ |
|
build: { |
|
outDir: '/dist/ssr', |
|
}, |
|
}), |
|
}, |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Terser for Minification |
|
DESCRIPTION: Installs Terser as a development dependency using npm. This is required when the `build.minify` option in Vite is set to `'terser'`. |
|
|
|
SOURCE: https://vite.dev/config/build-options |
|
|
|
LANGUAGE: sh |
|
CODE: |
|
``` |
|
npm add -D terser |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Trusted Certificate on macOS |
|
DESCRIPTION: Resolves network request issues in Chrome when using self-signed SSL certificates by installing a trusted certificate. This command adds a certificate to the login keychain. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db your-cert.cer |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite 4.3 Performance Benchmarks (Babel) |
|
DESCRIPTION: Benchmark results comparing Vite 4.2 and Vite 4.3 with Babel for development server startup and HMR times. Includes metrics for dev cold start, dev warm start, root HMR, and leaf HMR. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite4-3 |
|
|
|
LANGUAGE: markdown |
|
CODE: |
|
``` |
|
| **Vite (babel)** | Vite 4.2 | Vite 4.3 | Improvement | |
|
| --- | --- | --- | --- | |
|
| **dev cold start** | 17249.0ms | 5132.4ms | -70.2% | |
|
| **dev warm start** | 6027.8ms | 4536.1ms | -24.7% | |
|
| **Root HMR** | 46.8ms | 26.7ms | -42.9% | |
|
| **Leaf HMR** | 27.0ms | 12.9ms | -52.2% | |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite 3.0 Quick Links |
|
DESCRIPTION: Essential links for users transitioning to or learning about Vite 3.0, including access to the main documentation, migration guide, and detailed changelog. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite3 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Vite 3.0 Resources: |
|
|
|
- Docs: / |
|
- Migration Guide: https://v3.vite.dev/guide/migration |
|
- Changelog (v3.0.0): https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#300-2022-07-13 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite: Preview Server Function |
|
DESCRIPTION: Starts a Vite preview server. It takes an optional inline configuration object and returns a promise that resolves to a PreviewServer instance. The server can be used to print URLs, bind CLI shortcuts, and access underlying server components. |
|
|
|
SOURCE: https://vite.dev/guide/api-javascript |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
preview(inlineConfig?: InlineConfig): Promise<PreviewServer> |
|
- Starts a Vite preview server. |
|
- Parameters: |
|
- inlineConfig: Optional configuration object for the preview server. |
|
- Returns: |
|
- A Promise resolving to a PreviewServer instance. |
|
``` |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import { |
|
preview |
|
} from 'vite' |
|
|
|
const previewServer = await preview({ |
|
// any valid user config options, plus `mode` and `configFile` |
|
preview: { |
|
port: 8080, |
|
open: true, |
|
}, |
|
}) |
|
|
|
previewServer.printUrls() |
|
previewServer.bindCLIShortcuts({ print: true }) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: ViteDevServer.listen Method Signature |
|
DESCRIPTION: Provides the TypeScript signature for the `listen` method of the ViteDevServer, detailing its parameters and return type for starting the development server. |
|
|
|
SOURCE: https://vite.dev/index |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
ViteDevServer.listen(port?: number | undefined, isRestart?: boolean | undefined): Promise<ViteDevServer> |
|
- Starts the server. |
|
- Parameters: |
|
- port: Optional port number to listen on. |
|
- isRestart: Optional boolean indicating if this is a server restart. |
|
- Returns: A Promise that resolves to the ViteDevServer instance. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite 4.3 Performance Benchmarks (SWC) |
|
DESCRIPTION: Benchmark results comparing Vite 4.2 and Vite 4.3 with SWC for development server startup and HMR times. Includes metrics for dev cold start, dev warm start, root HMR, and leaf HMR. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite4-3 |
|
|
|
LANGUAGE: markdown |
|
CODE: |
|
``` |
|
| **Vite (swc)** | Vite 4.2 | Vite 4.3 | Improvement | |
|
| --- | --- | --- | --- | |
|
| **dev cold start** | 13552.5ms | 3201.0ms | -76.4% | |
|
| **dev warm start** | 4625.5ms | 2834.4ms | -38.7% | |
|
| **Root HMR** | 30.5ms | 24.0ms | -21.3% | |
|
| **Leaf HMR** | 16.9ms | 10.0ms | -40.8% | |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server FS Allow Example |
|
DESCRIPTION: Configures Vite's file system access control, allowing specific directories or files to be served via the /@fs/ URL. This example shows how to allow files one level above the project root. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
export default defineConfig({ |
|
server: { |
|
fs: { |
|
// Allow serving files from one level up to the project root |
|
allow: ['..'] |
|
} |
|
} |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Scaffold Vite Project with pnpm |
|
DESCRIPTION: Command to create a new Vite project using pnpm. It allows scaffolding with various frameworks and runtimes, providing a quick start for development. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite4 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm create vite |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Play Vite Online |
|
DESCRIPTION: Provides a quick way to experiment with Vite 6 in an online environment without local setup. This is useful for testing and exploring Vite's capabilities. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite6 |
|
|
|
LANGUAGE: url |
|
CODE: |
|
``` |
|
vite.new |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Worker Thread Transport Implementation |
|
DESCRIPTION: Example of implementing ModuleRunnerTransport for communication with a worker thread using Node.js's parentPort. This setup is used when the module runner operates in a separate worker context. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-runtimes |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { parentPort } from 'node:worker_threads' |
|
import { fileURLToPath } from 'node:url' |
|
import { ESModulesEvaluator, ModuleRunner } from 'vite/module-runner' |
|
|
|
/** @type {import('vite/module-runner').ModuleRunnerTransport} */ |
|
const transport = { |
|
connect({ onMessage, onDisconnection }) { |
|
parentPort.on('message', onMessage) |
|
parentPort.on('close', onDisconnection) |
|
}, |
|
send(data) { |
|
parentPort.postMessage(data) |
|
}, |
|
} |
|
|
|
const runner = new ModuleRunner( |
|
{ |
|
transport, |
|
}, |
|
new ESModulesEvaluator(), |
|
) |
|
|
|
await runner.import('/entry.js') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite HotUpdate Hook: Full Reload Example |
|
DESCRIPTION: An example of using the `hotUpdate` hook to manually invalidate modules and trigger a full page reload by returning an empty array and sending a 'full-reload' event. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-plugins |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
hotUpdate({ modules, timestamp }) { |
|
if (this.environment.name !== 'client') |
|
return |
|
|
|
// Invalidate modules manually |
|
const invalidatedModules = new Set() |
|
for (const mod of modules) { |
|
this.environment.moduleGraph.invalidateModule( |
|
mod, |
|
invalidatedModules, |
|
timestamp, |
|
true |
|
) |
|
} |
|
this.environment.hot.send({ type: 'full-reload' }) |
|
return [] |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Scaffold Vite Project with pnpm create vite-extra |
|
DESCRIPTION: Command to create a new Vite project using pnpm, providing access to additional templates like Solid, Deno, SSR, and library starters. This offers more specialized project setups. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite4 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm create vite-extra |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite's Production Transform Example |
|
DESCRIPTION: Illustrates how Vite transforms dynamic URL resolution during production builds. It maps a dynamic path to specific imported module assets, ensuring correct asset references. |
|
|
|
SOURCE: https://vite.dev/guide/assets |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import __img0png from './dir/img0.png' |
|
import __img1png from './dir/img1.png' |
|
|
|
function getImageUrl(name) { |
|
const modules = { |
|
'./dir/img0.png': __img0png, |
|
'./dir/img1.png': __img1png |
|
} |
|
return new URL(modules[`./dir/${name}.png`], import.meta.url).href |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Render Vite Assets in Production HTML (HTML) |
|
DESCRIPTION: Provides an example HTML template for rendering Vite assets in production. It demonstrates how to use the manifest file to link hashed CSS and JavaScript files. |
|
|
|
SOURCE: https://vite.dev/guide/backend-integration |
|
|
|
LANGUAGE: html |
|
CODE: |
|
``` |
|
<!-- if production --> |
|
|
|
<!-- for cssFile of manifest[name].css --> |
|
<link rel="stylesheet" href="/{{ cssFile }}" /> |
|
|
|
<!-- for chunk of importedChunks(manifest, name) --> |
|
<!-- for cssFile of chunk.css --> |
|
<link rel="stylesheet" href="/{{ cssFile }}" /> |
|
|
|
<script type="module" src="/{{ manifest[name].file }}"></script> |
|
|
|
<!-- for chunk of importedChunks(manifest, name) --> |
|
<link rel="modulepreload" href="/{{ chunk.file }}" /> |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite SSR Middleware Implementation |
|
DESCRIPTION: Provides a comprehensive example of setting up a Vite server in middleware mode and implementing an Express-like middleware to handle SSR requests. It covers reading the index.html, transforming it with Vite, importing the server entry point, rendering the application, and injecting the result into the HTML. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-frameworks |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import fs from 'node:fs' |
|
import path from 'node:path' |
|
import { fileURLToPath } from 'node:url' |
|
import { createServer } from 'vite' |
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url)) |
|
|
|
const viteServer = await createServer({ |
|
server: { middlewareMode: true }, |
|
appType: 'custom', |
|
environments: { |
|
server: { |
|
// by default, modules are run in the same process as the vite server |
|
}, |
|
}, |
|
}) |
|
|
|
// You might need to cast this to RunnableDevEnvironment in TypeScript or |
|
// use isRunnableDevEnvironment to guard the access to the runner |
|
const serverEnvironment = viteServer.environments.server |
|
|
|
app.use('*', async (req, res, next) => { |
|
const url = req.originalUrl |
|
|
|
// 1. Read index.html |
|
const indexHtmlPath = path.resolve(__dirname, 'index.html') |
|
let template = fs.readFileSync(indexHtmlPath, 'utf-8') |
|
|
|
// 2. Apply Vite HTML transforms. This injects the Vite HMR client, |
|
// and also applies HTML transforms from Vite plugins, e.g. global |
|
// preambles from @vitejs/plugin-react |
|
template = await viteServer.transformIndexHtml(url, template) |
|
|
|
// 3. Load the server entry. import(url) automatically transforms |
|
// ESM source code to be usable in Node.js! There is no bundling |
|
// required, and provides full HMR support. |
|
const { render } = await serverEnvironment.runner.import( |
|
'/src/entry-server.js', |
|
) |
|
|
|
// 4. render the app HTML. This assumes entry-server.js's exported |
|
// `render` function calls appropriate framework SSR APIs, |
|
// e.g. ReactDOMServer.renderToString() |
|
const appHtml = await render(url) |
|
|
|
// 5. Inject the app-rendered HTML into the template. |
|
const html = template.replace(`<!--ssr-outlet-->`, appHtml) |
|
|
|
// 6. Send the rendered HTML back. |
|
res.status(200).set({ 'Content-Type': 'text/html' }).end(html) |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Bare Module Import Example |
|
DESCRIPTION: Illustrates how Vite processes bare module imports, which are not natively supported by browsers. Vite rewrites these imports to valid URLs, enabling them to be resolved and served correctly, often after pre-bundling. |
|
|
|
SOURCE: https://vite.dev/guide/features |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { someMethod } from 'my-dep' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Debug Transform Logs |
|
DESCRIPTION: Example output from running Vite with the `--debug transform` flag. This helps identify files that take longer to transform, which can then be pre-warmed up by the development server. |
|
|
|
SOURCE: https://vite.dev/guide/performance |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
vite:transform 28.72ms /@vite/client +1ms |
|
vite:transform 62.95ms /src/components/BigComponent.vue +1ms |
|
vite:transform 102.54ms /src/utils/big-utils.js +1ms |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Setup Vite Dev Server with Express Middleware (JS) |
|
DESCRIPTION: This snippet demonstrates initializing an Express server and integrating Vite's development server in middleware mode. It configures Vite to disable its own HTML serving, allowing the parent server to manage requests. This setup is crucial for SSR applications where the Node.js server handles rendering. |
|
|
|
SOURCE: https://vite.dev/guide/ssr |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import fs from 'node:fs' |
|
import path from 'node:path' |
|
import { fileURLToPath } from 'node:url' |
|
import express from 'express' |
|
import { createServer as createViteServer } from 'vite' |
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url)) |
|
|
|
async function createServer() { |
|
const app = express() |
|
|
|
// Create Vite server in middleware mode and configure the app type as |
|
// 'custom', disabling Vite's own HTML serving logic so parent server |
|
// can take control |
|
const vite = await createViteServer({ |
|
server: { middlewareMode: true }, |
|
appType: 'custom' |
|
}) |
|
|
|
// Use vite's connect instance as middleware. If you use your own |
|
// express router (express.Router()), you should use router.use |
|
// When the server restarts (for example after the user modifies |
|
// vite.config.js), `vite.middlewares` is still going to be the same |
|
// reference (with a new internal stack of Vite and plugin-injected |
|
// middlewares). The following is valid even after restarts. |
|
|
|
app.use(vite.middlewares) |
|
|
|
app.use('*all', async (req, res) => { |
|
// serve index.html - we will tackle this next |
|
}) |
|
|
|
app.listen(5173) |
|
} |
|
|
|
createServer() |
|
|
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: HTTP Request Transport Implementation |
|
DESCRIPTION: Example of implementing ModuleRunnerTransport using fetch for HTTP requests to communicate with a server. This is suitable for environments where direct process communication is not feasible. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-runtimes |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import { ESModulesEvaluator, ModuleRunner } from 'vite/module-runner' |
|
|
|
export const runner = new ModuleRunner( |
|
{ |
|
transport: { |
|
async invoke(data) { |
|
const response = await fetch(`http://my-vite-server/invoke`, { |
|
method: 'POST', |
|
body: JSON.stringify(data), |
|
}) |
|
return response.json() |
|
}, |
|
}, |
|
hmr: false, // disable HMR as HMR requires transport.connect |
|
}, |
|
new ESModulesEvaluator(), |
|
) |
|
|
|
await runner.import('/entry.js') |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: GitHub Pages Deployment Workflow |
|
DESCRIPTION: A GitHub Actions workflow to automate the deployment of static content to GitHub Pages. It checks out code, sets up Node.js, installs dependencies, builds the project, configures pages, uploads the build artifact, and deploys. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: yaml |
|
CODE: |
|
``` |
|
# Simple workflow for deploying static content to GitHub Pages |
|
name: Deploy static content to Pages |
|
|
|
on: |
|
# Runs on pushes targeting the default branch |
|
push: |
|
branches: ['main'] |
|
|
|
# Allows you to run this workflow manually from the Actions tab |
|
workflow_dispatch: |
|
|
|
# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages |
|
permissions: |
|
contents: read |
|
pages: write |
|
id-token: write |
|
|
|
# Allow one concurrent deployment |
|
concurrency: |
|
group: 'pages' |
|
cancel-in-progress: true |
|
|
|
jobs: |
|
# Single deploy job since we're just deploying |
|
deploy: |
|
environment: |
|
name: github-pages |
|
url: ${{ steps.deployment.outputs.page_url }} |
|
runs-on: ubuntu-latest |
|
steps: |
|
- name: Checkout |
|
uses: actions/checkout@v4 |
|
- name: Set up Node |
|
uses: actions/setup-node@v4 |
|
with: |
|
node-version: lts/* |
|
cache: 'npm' |
|
- name: Install dependencies |
|
run: npm ci |
|
- name: Build |
|
run: npm run build |
|
- name: Setup Pages |
|
uses: actions/configure-pages@v5 |
|
- name: Upload artifact |
|
uses: actions/upload-pages-artifact@v3 |
|
with: |
|
# Upload dist folder |
|
path: './dist' |
|
- name: Deploy to GitHub Pages |
|
id: deployment |
|
uses: actions/deploy-pages@v4 |
|
|
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Config: Optimize Dependencies |
|
DESCRIPTION: Configuration example for Vite's dependency optimization in `vite.config.js`. It demonstrates how to use `optimizeDeps.include` and `build.commonjsOptions.include` to manage linked dependencies in monorepos and ensure proper bundling of CommonJS modules. |
|
|
|
SOURCE: https://vite.dev/guide/dep-pre-bundling |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
export default defineConfig({ |
|
optimizeDeps: { |
|
include: ['linked-dep'], |
|
}, |
|
build: { |
|
commonjsOptions: { |
|
include: [/linked-dep/, /node_modules/], |
|
}, |
|
}, |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Server-Side HTTP Invoke Handler |
|
DESCRIPTION: Example of how a server can handle incoming HTTP requests for the 'invoke' operation from a ModuleRunnerTransport. This demonstrates processing the payload and returning the result or error. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-runtimes |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
const customEnvironment = new DevEnvironment(name, config, context) |
|
|
|
server.onRequest((request: Request) => { |
|
const url = new URL(request.url) |
|
if (url.pathname === '/invoke') { |
|
const payload = (await request.json()) as HotPayload |
|
const result = customEnvironment.hot.handleInvoke(payload) |
|
return new Response(JSON.stringify(result)) |
|
} |
|
return Response.error() |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Cloudflare Pages Deployment via Wrangler |
|
DESCRIPTION: Steps to deploy a Vite application to Cloudflare Pages using the Wrangler CLI. This involves installing Wrangler, logging in, building the project, and deploying the 'dist' directory. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
# Install Wrangler CLI |
|
$ npm install -g wrangler |
|
|
|
# Login to Cloudflare account from CLI |
|
$ wrangler login |
|
|
|
# Run your build command |
|
$ npm run build |
|
|
|
# Create new deployment |
|
$ npx wrangler pages deploy dist |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Version Documentation Links |
|
DESCRIPTION: Provides direct links to the documentation for various major versions of Vite, allowing users to access specific version guides and features. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite3 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Vite Version Docs: |
|
|
|
- Vite 6 Docs: https://v6.vite.dev |
|
- Vite 5 Docs: https://v5.vite.dev |
|
- Vite 4 Docs: https://v4.vite.dev |
|
- Vite 3 Docs: https://v3.vite.dev |
|
- Vite 2 Docs: https://v2.vite.dev |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Vite Dev Server with Basic Configuration |
|
DESCRIPTION: Demonstrates how to programmatically create a Vite development server using `createServer`. It shows setting the root directory, port, and binding CLI shortcuts. |
|
|
|
SOURCE: https://vite.dev/guide/api-javascript |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import { |
|
fileURLToPath |
|
} from 'node:url' |
|
import { |
|
createServer |
|
} from 'vite' |
|
|
|
const __dirname = fileURLToPath(new URL('.', import.meta.url)) |
|
|
|
const server = await createServer({ |
|
// any valid user config options, plus `mode` and `configFile` |
|
configFile: false, |
|
root: __dirname, |
|
server: { |
|
port: 1337 |
|
} |
|
}) |
|
|
|
await server.listen() |
|
server.printUrls() |
|
server.bindCLIShortcuts({ print: true }) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: GitLab CI for GitLab Pages |
|
DESCRIPTION: A GitLab CI configuration file to build and deploy a Vite application to GitLab Pages. It uses a Node.js Docker image, installs dependencies, builds the project, and copies the output to the public directory for GitLab Pages. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: yaml |
|
CODE: |
|
``` |
|
image: node:lts |
|
pages: |
|
stage: deploy |
|
cache: |
|
key: |
|
files: |
|
- package-lock.json |
|
prefix: npm |
|
paths: |
|
- node_modules/ |
|
script: |
|
- npm install |
|
- npm run build |
|
- cp -a dist/. public/ |
|
artifacts: |
|
paths: |
|
- public |
|
rules: |
|
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH |
|
|
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Plugin Authoring Guide |
|
DESCRIPTION: Guidance on creating Vite plugins, emphasizing extension of Rollup's plugin interface and Vite-specific options. It suggests checking existing features and community plugins before authoring, and provides tips for inlining plugins in vite.config.js and using vite-plugin-inspect for debugging. |
|
|
|
SOURCE: https://vite.dev/guide/api-plugin |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Plugin API Overview: |
|
Extends Rollup's plugin interface with Vite-specific options. |
|
Works for both development and build. |
|
|
|
Authoring a Plugin: |
|
- Check Vite Features guide first. |
|
- Review community plugins (Rollup compatible and Vite specific). |
|
- Can be inlined in vite.config.js. |
|
- Consider sharing useful plugins. |
|
|
|
Debugging Tip: |
|
- Use vite-plugin-inspect for intermediate state inspection. |
|
- Install: npm install vite-plugin-inspect --save-dev |
|
- Visit: localhost:5173/__inspect/ to inspect modules and transformation stack. |
|
|
|
Configuration Example (Conceptual): |
|
// vite.config.js |
|
import myPlugin from './my-vite-plugin'; |
|
|
|
export default { |
|
plugins: [ |
|
myPlugin({ |
|
// plugin options |
|
}), |
|
// other plugins... |
|
] |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Configuration Options |
|
DESCRIPTION: Configuration options for Vite's development server. `server.warmup` pre-transforms modules for faster startup, and `server.open` automatically opens the app in the browser. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite5 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
server.warmup: object | object[] |
|
Description: Define a list of modules that should be pre-transformed as soon as the server starts to improve startup time. |
|
Example: |
|
server: { |
|
warmup: [ |
|
'/src/main.js', |
|
'/src/components/MyComponent.vue' |
|
] |
|
} |
|
|
|
server.open: boolean | string |
|
Description: Automatically open the app in the browser when the dev server starts. If true, Vite will open the default entry point. If a string, Vite will open the provided URL. |
|
Default: false |
|
Example: |
|
server: { |
|
open: true |
|
} |
|
server: { |
|
open: '/dashboard' |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Handling ESM-Only Packages in Vite Config |
|
DESCRIPTION: Explains how to resolve issues when importing ESM-only packages using `require` in Vite's configuration file. It provides recommended solutions for compatibility. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Error: Failed to resolve "foo". This package is ESM only but it was tried to load by `require`. |
|
Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/dependency.js from /path/to/vite.config.js not supported. Instead change the require of index.js in /path/to/vite.config.js to a dynamic import() which is available in all CommonJS modules. |
|
|
|
Description: |
|
This error arises when attempting to load an ECMAScript Module (ESM) only package using Node.js's `require` function, which is not supported by default in older Node.js versions (<=22) when loading ESM. Dynamic import() is the recommended approach. |
|
|
|
Resolution: |
|
Convert your Vite configuration file to use ESM: |
|
1. Add `"type": "module"` to the nearest `package.json` file. |
|
OR |
|
2. Rename your configuration file from `vite.config.js` or `vite.config.ts` to `vite.config.mjs` or `vite.config.mts` respectively. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Migration to Vite 6 |
|
DESCRIPTION: Guidance for updating projects to Vite 6, advising a review of the detailed Migration Guide for a straightforward update process. The complete list of changes is available in the official Vite 6 Changelog. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite6 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Migrating to Vite 6: |
|
Process: Generally straightforward for most projects. |
|
Recommendation: Review the detailed Migration Guide before upgrading. |
|
Resources: |
|
- Detailed Migration Guide: /guide/migration |
|
- Vite 6 Changelog: https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#500-2024-11-26 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Vite Virtual Module Plugin (JavaScript) |
|
DESCRIPTION: Example of a Vite plugin that implements the virtual module convention. It defines how to resolve and load custom modules during the build process, enabling build-time information injection into source files. |
|
|
|
SOURCE: https://vite.dev/guide/api-plugin |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
export default function myPlugin() { |
|
const virtualModuleId = 'virtual:my-module' |
|
const resolvedVirtualModuleId = '\0' + virtualModuleId |
|
|
|
return { |
|
name: 'my-plugin', // required, will show up in warnings and errors |
|
resolveId(id) { |
|
if (id === virtualModuleId) { |
|
return resolvedVirtualModuleId |
|
} |
|
}, |
|
load(id) { |
|
if (id === resolvedVirtualModuleId) { |
|
return `export const msg = "from virtual module"` |
|
} |
|
}, |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Build for Production with Vite CLI |
|
DESCRIPTION: Run the `vite build` command to create an optimized production bundle for your Vite application. By default, it uses `<root>/index.html` as the entry point and generates static assets suitable for hosting. |
|
|
|
SOURCE: https://vite.dev/guide/build |
|
|
|
LANGUAGE: CLI |
|
CODE: |
|
``` |
|
vite build |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite CLI Path Error on Windows |
|
DESCRIPTION: Addresses an error where Vite cannot find its module on Windows due to special characters like '&' in the project path. It suggests workarounds to resolve this issue. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Error: Cannot find module 'C:\\foo\\bar&baz\\vite\\bin\\vite.js' |
|
|
|
Description: |
|
This error occurs on Windows when the project folder path contains special characters, specifically '&', which is not handled correctly by npm's cmd-shim. |
|
|
|
Resolution: |
|
1. Switch to an alternative package manager like `pnpm` or `yarn`. |
|
2. Remove the special character '&' from the project directory path. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Self-Accepting Module Invalidation Example |
|
DESCRIPTION: Demonstrates how a self-accepting module can detect it cannot handle an HMR update and then invalidate itself, propagating the update requirement to its importers. |
|
|
|
SOURCE: https://vite.dev/guide/api-hmr |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import.meta.hot.accept((module) => { |
|
// You may use the new module instance to decide whether to invalidate. |
|
if (cannotHandleUpdate(module)) { |
|
import.meta.hot.invalidate() |
|
} |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Scaffold Vite Project |
|
DESCRIPTION: Use the Vite CLI to quickly create new projects with your preferred framework. Supports various templates including framework-specific starters and additional options via `vite-extra`. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite5 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm create vite |
|
pnpm create vite-extra |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Profile Vite Build Performance |
|
DESCRIPTION: To diagnose performance bottlenecks during the Vite build process, you can enable the Node.js inspector. This allows you to generate a CPU profile for analysis. Use the `--profile` flag with the `vite build` command. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
vite build --profile |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Windows subst command for virtual drives |
|
DESCRIPTION: The `subst` command in Windows creates a virtual drive linked to a folder. If your project resides on such a virtual drive, Vite may encounter issues. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
subst <driveletter>: <path> |
|
|
|
Example: |
|
subst Z: C:\MyProject\Frontend |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server Origin Example |
|
DESCRIPTION: Sets a custom origin for asset URLs generated by Vite during development. This is useful for scenarios where the development server runs on a different origin than the final deployment. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
export default defineConfig({ |
|
server: { |
|
origin: 'http://127.0.0.1:8080' |
|
} |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Plugin: Load and Transform Index.html via Virtual Module |
|
DESCRIPTION: Provides an example of a Vite plugin that resolves and loads a virtual module for `index.html`. It demonstrates reading the HTML file, transforming it using Vite's `transformIndexHtml` API, and exporting the content, including watching the source file. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-frameworks |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import fs from 'fs' |
|
import { Plugin, ViteDevServer } from 'vite' |
|
|
|
function vitePluginVirtualIndexHtml(): Plugin { |
|
let server: ViteDevServer | undefined |
|
return { |
|
name: vitePluginVirtualIndexHtml.name, |
|
configureServer(server_) { |
|
server = server_ |
|
}, |
|
resolveId(source) { |
|
return source === 'virtual:index-html' ? '\0' + source : undefined |
|
}, |
|
async load(id) { |
|
if (id === '\0' + 'virtual:index-html') { |
|
let html: string |
|
if (server) { |
|
this.addWatchFile('index.html') |
|
html = fs.readFileSync('index.html', 'utf-8') |
|
html = await server.transformIndexHtml('/', html) |
|
} else { |
|
html = fs.readFileSync('dist/client/index.html', 'utf-8') |
|
} |
|
return `export default ${JSON.stringify(html)}` |
|
} |
|
return |
|
}, |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Vite Extra Templates |
|
DESCRIPTION: Accesses additional Vite starter templates for various frameworks and runtimes, including Solid, Deno, SSR, and library starters. This command is also accessible via the 'Others' option in `create vite`. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite6 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm create vite-extra |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Increase Linux File Descriptor Limits |
|
DESCRIPTION: Addresses issues where requests stall on Linux due to file descriptor limits. Provides commands to temporarily increase limits for file descriptors and inotify, and suggests configuration file modifications for persistence. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# Check current limit |
|
$ ulimit -Sn |
|
# Change limit (temporary) |
|
$ ulimit -Sn 10000 # You might need to change the hard limit too |
|
# Restart your browser |
|
|
|
# Check current limits |
|
$ sysctl fs.inotify |
|
# Change limits (temporary) |
|
$ sudo sysctl fs.inotify.max_queued_events=16384 |
|
$ sudo sysctl fs.inotify.max_user_instances=8192 |
|
$ sudo sysctl fs.inotify.max_user_watches=524288 |
|
|
|
# For persistent changes, uncomment and add to systemd config files: |
|
# /etc/systemd/system.conf |
|
# /etc/systemd/user.conf |
|
# DefaultLimitNOFILE=65536 |
|
|
|
# For Ubuntu Linux, alternatively edit /etc/security/limits.conf: |
|
# * - nofile 65536 |
|
|
|
# Note: A restart is required for persistent changes. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Profile Vite Dev Server Performance |
|
DESCRIPTION: To diagnose performance bottlenecks in the Vite development server, you can enable the Node.js inspector. This allows you to generate a CPU profile for analysis. Use the `--profile` flag with the `vite` command and `--open` to automatically launch the application. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
vite --profile --open |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: React Support with @vitejs/plugin-react-swc |
|
DESCRIPTION: Replaces Babel with SWC for faster development builds, especially for large projects. It uses SWC and esbuild during production builds, significantly improving cold start and HMR performance. |
|
|
|
SOURCE: https://vite.dev/plugins |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import reactSwc from '@vitejs/plugin-react-swc' |
|
|
|
export default { |
|
plugins: [ |
|
reactSwc() |
|
] |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Client-Side Custom HMR Handler |
|
DESCRIPTION: Example of client-side JavaScript code that listens for custom HMR events sent from the server (e.g., 'special-update') and executes custom update logic. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-plugins |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
if (import.meta.hot) { |
|
import.meta.hot.on('special-update', (data) => { |
|
// perform custom update |
|
}) |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite File Change Detection (WSL2) |
|
DESCRIPTION: Explains potential issues with Vite not detecting file changes when running on WSL2. It suggests configuring the `server.watch` option to ensure file changes are monitored correctly. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: config |
|
CODE: |
|
``` |
|
# vite.config.js or vite.config.ts |
|
import { defineConfig } from 'vite' |
|
|
|
export default defineConfig({ |
|
server: { |
|
watch: { |
|
// Options to configure file watching |
|
// e.g., usePolling: true if file system events are not reliable |
|
} |
|
} |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Windows mklink command for symlinks/junctions |
|
DESCRIPTION: The `mklink` command in Windows creates symbolic links or directory junctions. Using `mklink` to link to a different drive, such as for a Yarn global cache, can cause Vite to fail. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
mklink [/D | /H | /J] <Link> <Target> |
|
|
|
Example for a directory junction: |
|
mklink /J C:\Users\User\.yarn C:\Users\User\AppData\Local\Yarn\global |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Preview Server Hook in Vite |
|
DESCRIPTION: The configurePreviewServer hook allows customization of the Vite preview server. It is called before other middlewares are installed. Returning a function from this hook enables injecting middleware after internal middlewares are set up, providing a post-setup hook. |
|
|
|
SOURCE: https://vite.dev/guide/api-plugin |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
const myPlugin = () => ({ |
|
name: 'configure-preview-server', |
|
configurePreviewServer(server) { |
|
// return a post hook that is called after other middlewares are |
|
// installed |
|
return () => { |
|
server.middlewares.use((req, res, next) => { |
|
// custom handle request... |
|
}) |
|
} |
|
}, |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite API Migration: Server to Environment Instances |
|
DESCRIPTION: Guides Vite plugin authors on migrating from deprecated ViteDevServer methods to their new locations within DevEnvironment instances. This change is crucial for compatibility with Vite v6 and beyond. |
|
|
|
SOURCE: https://vite.dev/changes/per-environment-apis |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Vite API Migration Guide: |
|
|
|
This section outlines the migration path for Vite plugin authors from deprecated `ViteDevServer` methods to the new `DevEnvironment` instances, introduced in Vite v6. |
|
|
|
**Motivation:** |
|
In Vite v5 and earlier, a single Vite dev server managed both `client` and `ssr` environments. APIs like `server.moduleGraph` and `server.transformRequest` handled modules from both, often requiring an `ssr` boolean parameter. Vite v6 allows for multiple custom environments (e.g., `client`, `ssr`, `edge`). To accommodate this, methods have been moved to the respective `environment` instances, simplifying their usage and removing the need for an `ssr` flag. |
|
|
|
**Affected Scope:** Vite Plugin Authors |
|
|
|
**Future Deprecation:** |
|
Deprecation of `server.moduleGraph` and other methods now located in environments is planned for a future major release. It is not recommended to move away from server methods immediately, but identifying usage is advised. |
|
|
|
**Migration Steps:** |
|
|
|
* **Module Graph Access:** |
|
- **Old:** `server.moduleGraph` |
|
- **New:** `environment.moduleGraph` |
|
- **Reference:** [/guide/api-environment-instances#separate-module-graphs](/guide/api-environment-instances#separate-module-graphs) |
|
|
|
* **Transform Request:** |
|
- **Old:** `server.transformRequest(url, { ssr })` |
|
- **New:** `environment.transformRequest(url)` |
|
|
|
* **Warmup Request:** |
|
- **Old:** `server.warmupRequest(url, { ssr })` |
|
- **New:** `environment.warmupRequest(url)` |
|
|
|
**Example of API Usage Change:** |
|
|
|
```javascript |
|
// Before Vite v6 |
|
async function handleRequest(server, url, ssr) { |
|
const module = await server.moduleGraph.getModuleByUrl(url, ssr); |
|
const transformed = await server.transformRequest(url, { ssr }); |
|
await server.warmupRequest(url, { ssr }); |
|
// ... |
|
} |
|
|
|
// After Vite v6 (using a specific environment instance) |
|
async function handleRequest(environment, url) { |
|
const module = await environment.moduleGraph.getModuleByUrl(url); |
|
const transformed = await environment.transformRequest(url); |
|
await environment.warmupRequest(url); |
|
// ... |
|
} |
|
``` |
|
|
|
**Related Methods/Concepts:** |
|
- `DevEnvironment` instances: Allow creation of custom environments beyond `client` and `ssr`. |
|
- `server.moduleGraph`: Previously held modules from all environments, now separated per `DevEnvironment`. |
|
- `server.transformRequest`: Previously required an `ssr` option, now context-aware within the `environment`. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create Workerd Development Environment |
|
DESCRIPTION: Provides an example of a TypeScript function `createWorkerdDevEnvironment` that instantiates Vite's `DevEnvironment`. It sets up custom resolve conditions and a `HotChannel` for communication, enabling hot module replacement for the Workerd runtime. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-runtimes |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import { DevEnvironment, HotChannel } from 'vite' |
|
|
|
function createWorkerdDevEnvironment( |
|
name: string, |
|
config: ResolvedConfig, |
|
context: DevEnvironmentContext |
|
) { |
|
const connection = /* ... */ |
|
const transport: HotChannel = { |
|
on: (listener) => { connection.on('message', listener) }, |
|
send: (data) => connection.send(data), |
|
} |
|
|
|
const workerdDevEnvironment = new DevEnvironment(name, config, { |
|
options: { |
|
resolve: { conditions: ['custom'] }, |
|
...context.options, |
|
}, |
|
hot: true, |
|
transport, |
|
}) |
|
return workerdDevEnvironment |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Scaffold Vite Project (Basic) |
|
DESCRIPTION: Commands to create a new Vite project using different package managers. These commands initiate the project scaffolding process, prompting the user for project name and framework selection. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npm create vite@latest |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ yarn create vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ pnpm create vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ bun create vite |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ deno init --npm vite |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Basic Vite HTML Entry Point |
|
DESCRIPTION: A minimal HTML file that serves as the entry point for a Vite project during development. |
|
|
|
SOURCE: https://vite.dev/guide |
|
|
|
LANGUAGE: html |
|
CODE: |
|
``` |
|
<p>Hello Vite!</p> |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server HTTPS Configuration |
|
DESCRIPTION: Enables TLS + HTTP/2 for the development server. Accepts an options object compatible with Node.js's `https.createServer()`. A basic setup can use `@vitejs/plugin-basic-ssl`, but custom certificates are recommended. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
server.https |
|
Type: https.ServerOptions |
|
Description: Enable TLS + HTTP/2. The value is an options object passed to `https.createServer()`. Note that this downgrades to TLS only when the `server.proxy` option is also used. A valid certificate is needed. For a basic setup, you can add `@vitejs/plugin-basic-ssl` to the project plugins, which will automatically create and cache a self-signed certificate. But we recommend creating your own certificates. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Server Auto Open Configuration |
|
DESCRIPTION: Configures automatic browser opening upon server start. Can be a boolean to open the default URL or a string to specify a pathname. Environment variables `process.env.BROWSER` and `process.env.BROWSER_ARGS` can customize the browser and arguments. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
export default defineConfig({ |
|
server: { |
|
open: '/docs/index.html', |
|
}, |
|
}) |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
server.open |
|
Type: boolean | string |
|
Description: Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname. If you want to open the server in a specific browser you like, you can set the env `process.env.BROWSER` (e.g. `firefox`). You can also set `process.env.BROWSER_ARGS` to pass additional arguments (e.g. `--incognito`). `BROWSER` and `BROWSER_ARGS` are also special environment variables you can set in the `.env` file to configure it. See the `open` package for more details. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite: Configure server.sourcemapIgnoreList |
|
DESCRIPTION: Example of configuring the `server.sourcemapIgnoreList` option in Vite. This function determines which source files should be ignored in the server's sourcemap, defaulting to ignoring files within `node_modules`. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { defineConfig } from 'vite'; |
|
|
|
export default defineConfig({ |
|
server: { |
|
// This is the default value, and will add all files with node_modules |
|
// in their paths to the ignore list. |
|
sourcemapIgnoreList(sourcePath, sourcemapPath) { |
|
return sourcePath.includes('node_modules'); |
|
}, |
|
}, |
|
}); |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Configuration: Terser Minification |
|
DESCRIPTION: Configuration option to enable Terser as the minifier for JavaScript and CSS builds in Vite. If this option is used, the 'terser' package must be installed as a development dependency. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite3 |
|
|
|
LANGUAGE: JavaScript |
|
CODE: |
|
``` |
|
build: { |
|
minify: 'terser' |
|
} |
|
``` |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
npm add -D terser |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Transform Custom File Types |
|
DESCRIPTION: Provides an example of a Vite/Rollup plugin factory function designed to transform custom file extensions. It uses the `transform` hook to compile files with a specific extension into JavaScript. |
|
|
|
SOURCE: https://vite.dev/guide/api-plugin |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
const fileRegex = /\.(my-file-ext)$/ |
|
|
|
export default function myPlugin() { |
|
return { |
|
name: 'transform-file', |
|
|
|
transform(src, id) { |
|
if (fileRegex.test(id)) { |
|
return { |
|
code: compileFileToJS(src), |
|
map: null, // provide source map if available |
|
} |
|
} |
|
}, |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Add Legacy Browser Support Plugin in Vite |
|
DESCRIPTION: Demonstrates how to add the official @vitejs/plugin-legacy to a Vite project to support older browsers. This involves installing the plugin as a dev dependency and configuring it within vite.config.js to specify target browser versions. |
|
|
|
SOURCE: https://vite.dev/guide/using-plugins |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
npm add -D @vitejs/plugin-legacy |
|
``` |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import legacy from '@vitejs/plugin-legacy' |
|
import { defineConfig } from 'vite' |
|
|
|
export default defineConfig({ |
|
plugins: [ |
|
legacy({ |
|
targets: ['defaults', 'not IE 11'], |
|
}), |
|
], |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Glob Import Named Imports |
|
DESCRIPTION: Explains how to import specific exports from modules using the `import` option in `import.meta.glob`. This allows targeting named exports (e.g., `setup`) or the default export, improving tree-shaking and reducing bundle size when only specific parts of modules are needed. |
|
|
|
SOURCE: https://vite.dev/guide/features |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
const modules = import.meta.glob('./dir/*.js', { |
|
import: 'setup' |
|
}) |
|
``` |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
// code produced by vite |
|
const modules = { |
|
'./dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup), |
|
'./dir/foo.js': () => import('./dir/foo.js').then((m) => m.setup), |
|
} |
|
``` |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
const modules = import.meta.glob('./dir/*.js', { |
|
import: 'setup', |
|
eager: true, |
|
}) |
|
``` |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
// code produced by vite: |
|
import { setup as __vite_glob_0_0 } from './dir/bar.js' |
|
import { setup as __vite_glob_0_1 } from './dir/foo.js' |
|
const modules = { |
|
'./dir/bar.js': __vite_glob_0_0, |
|
'./dir/foo.js': __vite_glob_0_1, |
|
} |
|
``` |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
const modules = import.meta.glob('./dir/*.js', { |
|
import: 'default', |
|
eager: true, |
|
}) |
|
``` |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
// code produced by vite: |
|
import { default as __vite_glob_0_0 } from './dir/bar.js' |
|
import { default as __vite_glob_0_1 } from './dir/foo.js' |
|
const modules = { |
|
'./dir/bar.js': __vite_glob_0_0, |
|
'./dir/foo.js': __vite_glob_0_1, |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Profile Vite Dev Server Startup |
|
DESCRIPTION: Use the `vite --profile` command to generate a CPU profile of the Vite development server startup. This profile can be analyzed with tools like speedscope to identify performance bottlenecks. Press 'p' after the page loads to trigger the profile saving. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite4-3 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
vite --profile |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: HMR Full Reload Troubleshooting |
|
DESCRIPTION: Explains why a full reload might occur instead of HMR. This happens when HMR is not handled by Vite or a plugin, or if a circular dependency is detected, requiring a reload to maintain execution order. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# To diagnose circular dependencies triggering full reloads: |
|
vite --debug hmr |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Core APIs Overview |
|
DESCRIPTION: Overview of the main APIs provided by Vite for plugin development, Hot Module Replacement, and general JavaScript integration. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Plugin API: |
|
Used for extending Vite's functionality through custom plugins. |
|
|
|
HMR API: |
|
Provides methods for managing Hot Module Replacement during development. |
|
|
|
JavaScript API: |
|
Offers programmatic access to Vite's features and configuration. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite build.cssTarget Configuration |
|
DESCRIPTION: Allows setting a specific browser target for CSS minification, separate from the JavaScript transpilation target. This is useful for non-mainstream browsers that might have different CSS feature support. For example, targeting `chrome61` can prevent transformation of `rgba()` to `#RGBA` hex notation. |
|
|
|
SOURCE: https://vite.dev/config/build-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
build.cssTarget: |
|
Type: string | string[] |
|
Default: the same as [`build.target`](#build-target) |
|
Description: This option allows users to set a different browser target for CSS minification from the one used for JavaScript transpilation. It should only be used when targeting a non-mainstream browser. For example, Android WeChat WebView supports modern JS but not `#RGBA` hex colors in CSS, requiring `build.cssTarget` to be set to `chrome61` to prevent Vite from transforming `rgba()` colors. |
|
Example: |
|
// Target CSS for Chrome 61 compatibility |
|
// build: { |
|
// cssTarget: 'chrome61' |
|
// } |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite HotUpdate Hook: Custom Event Example |
|
DESCRIPTION: Demonstrates using the `hotUpdate` hook to send a custom HMR event ('special-update') to the client for custom update logic, returning an empty array to prevent default handling. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-plugins |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
hotUpdate() { |
|
if (this.environment.name !== 'client') |
|
return |
|
|
|
this.environment.hot.send({ |
|
type: 'custom', |
|
event: 'special-update', |
|
data: {} |
|
}) |
|
return [] |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Vite Host for VS Code Devcontainers |
|
DESCRIPTION: Fixes issues with port forwarding in VS Code Dev Containers by setting the server host option. This is necessary because VS Code's port forwarding does not support IPv6. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: config |
|
CODE: |
|
``` |
|
# vite.config.js or vite.config.ts |
|
import { defineConfig } from 'vite' |
|
|
|
export default defineConfig({ |
|
server: { |
|
host: '127.0.0.1' |
|
} |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Resolve Static Asset URL |
|
DESCRIPTION: Demonstrates how to use `new URL` with `import.meta.url` to get the resolved URL of a static asset like an image. This pattern is natively supported by Vite for development and ensures correct asset paths after production bundling. |
|
|
|
SOURCE: https://vite.dev/guide/assets |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
const imgUrl = new URL('./img.png', import.meta.url).href |
|
|
|
document.getElementById('hero-img').src = imgUrl |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Deploy to Surge |
|
DESCRIPTION: Deploy your Vite static site using the Surge CLI. This involves building your project and then using the 'surge' command with the distribution directory. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
npm run build |
|
surge dist |
|
``` |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
surge dist yourdomain.com |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Build CLI Options |
|
DESCRIPTION: Configures the main Vite build process. These options control output directories, asset handling, source maps, minification, and watch modes. |
|
|
|
SOURCE: https://vite.dev/guide/cli |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Vite CLI Build Options: |
|
|
|
--target <target> |
|
Transpile target (default: "modules") (string) |
|
|
|
--outDir <dir> |
|
Output directory (default: dist) (string) |
|
|
|
--assetsDir <dir> |
|
Directory under outDir to place assets in (default: "assets") (string) |
|
|
|
--assetsInlineLimit <number> |
|
Static asset base64 inline threshold in bytes (default: 4096) (number) |
|
|
|
--ssr [entry] |
|
Build specified entry for server-side rendering (string) |
|
|
|
--sourcemap [output] |
|
Output source maps for build (default: false) (boolean | "inline" | "hidden") |
|
|
|
--minify [minifier] |
|
Enable/disable minification, or specify minifier to use (default: "esbuild") (boolean | "terser" | "esbuild") |
|
|
|
--manifest [name] |
|
Emit build manifest json (boolean | string) |
|
|
|
--ssrManifest [name] |
|
Emit ssr manifest json (boolean | string) |
|
|
|
--emptyOutDir |
|
Force empty outDir when it's outside of root (boolean) |
|
|
|
-w, --watch |
|
Rebuilds when modules have changed on disk (boolean) |
|
|
|
-c, --config <file> |
|
Use specified config file (string) |
|
|
|
--base <path> |
|
Public base path (default: "/") (string) |
|
|
|
-l, --logLevel <level> |
|
Info | warn | error | silent (string) |
|
|
|
--clearScreen |
|
Allow/disable clear screen when logging (boolean) |
|
|
|
--configLoader <loader> |
|
Use `bundle` to bundle the config with esbuild or `runner` (experimental) to process it on the fly (default: `bundle`) (string) |
|
|
|
--profile |
|
Start built-in Node.js inspector (check [Performance bottlenecks](/guide/troubleshooting#performance-bottlenecks)) |
|
|
|
-d, --debug [feat] |
|
Show debug logs (string | boolean) |
|
|
|
-f, --filter <filter> |
|
Filter debug logs (string) |
|
|
|
-m, --mode <mode> |
|
Set env mode (string) |
|
|
|
-h, --help |
|
Display available CLI options |
|
|
|
--app |
|
Build all environments, same as `builder: {}` (boolean, experimental) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Preview Configuration Options |
|
DESCRIPTION: Comprehensive documentation for Vite's preview server configuration. This section details options for network binding, allowed hosts, port management, HTTPS, and automatic browser opening. |
|
|
|
SOURCE: https://vite.dev/config/preview-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
Preview Options: |
|
Unless noted, the options in this section are only applied to preview. |
|
|
|
preview.host: |
|
- Type: string | boolean |
|
- Default: `server.host` |
|
- Description: Specify which IP addresses the server should listen on. Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses. This can be set via the CLI using `--host 0.0.0.0` or `--host`. |
|
- NOTE: There are cases when other servers might respond instead of Vite. See `server.host` for more details. |
|
|
|
preview.allowedHosts: |
|
- Type: string | true |
|
- Default: `server.allowedHosts` |
|
- Description: The hostnames that Vite is allowed to respond to. See `server.allowedHosts` for more details. |
|
|
|
preview.port: |
|
- Type: number |
|
- Default: 4173 |
|
- Description: Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. |
|
- Example: |
|
export default defineConfig({ |
|
server: { |
|
port: 3030, |
|
}, |
|
preview: { |
|
port: 8080, |
|
}, |
|
}) |
|
|
|
preview.strictPort: |
|
- Type: boolean |
|
- Default: `server.strictPort` |
|
- Description: Set to `true` to exit if port is already in use, instead of automatically trying the next available port. |
|
|
|
preview.https: |
|
- Type: https.ServerOptions |
|
- Default: `server.https` |
|
- Description: Enable TLS + HTTP/2. See `server.https` for more details. |
|
|
|
preview.open: |
|
- Type: boolean | string |
|
- Default: `server.open` |
|
- Description: Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname. If you want to open the server in a specific browser you like, you can set the env `process.env.BROWSER` (e.g. `firefox`). You can also set `process.env.BROWSER_ARGS` to pass additional arguments (e.g. `--incognito`). `BROWSER` and `BROWSER_ARGS` are also special environment variables you can set in the `.env` file to configure it. See [the `open` package](https://github.com/sindresorhus/open#app) for more details. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Deploy to Render |
|
DESCRIPTION: Deploy your Vite static site on Render. This involves creating a new Static Site, connecting a repository, and specifying the build command and publish directory. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# Build Command: npm install && npm run build |
|
# Publish Directory: dist |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Update package.json dev script (Diff) |
|
DESCRIPTION: This diff shows how to modify the `dev` script in `package.json`. Instead of running Vite directly, it now executes the custom `server.js` script. This ensures that the Node.js server, configured with Vite in middleware mode, is started when you run `npm run dev`. |
|
|
|
SOURCE: https://vite.dev/guide/ssr |
|
|
|
LANGUAGE: diff |
|
CODE: |
|
``` |
|
"scripts": { |
|
- "dev": "vite" |
|
+ "dev": "node server" |
|
} |
|
|
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Deploy to Kinsta |
|
DESCRIPTION: Deploy your static site using Kinsta Static Site Hosting by following their provided instructions for React and Vite applications. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# Follow Kinsta's guide for Vite quickstart. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure Vite Server Proxy Rules |
|
DESCRIPTION: Defines custom proxy rules for the Vite development server. Supports string shorthand, options objects, and RegExp for flexible request routing. Any requests starting with a configured key will be proxied to the specified target. Extends http-proxy options. |
|
|
|
SOURCE: https://vite.dev/config/server-options |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
export default defineConfig({ |
|
server: { |
|
proxy: { |
|
// string shorthand: |
|
// http://localhost:5173/foo |
|
// -> http://localhost:4567/foo |
|
'/foo': 'http://localhost:4567', |
|
// with options: |
|
// http://localhost:5173/api/bar |
|
// -> http://jsonplaceholder.typicode.com/bar |
|
'/api': { |
|
target: 'http://jsonplaceholder.typicode.com', |
|
changeOrigin: true, |
|
rewrite: (path) => path.replace(/^\/api/, ''), |
|
}, |
|
// with RegExp: |
|
// http://localhost:5173/fallback/ |
|
// -> http://jsonplaceholder.typicode.com/ |
|
'^/fallback/.*': { |
|
target: 'http://jsonplaceholder.typicode.com', |
|
changeOrigin: true, |
|
rewrite: (path) => path.replace(/^\/fallback/, ''), |
|
}, |
|
// Using the proxy instance |
|
'/api': { |
|
target: 'http://jsonplaceholder.typicode.com', |
|
changeOrigin: true, |
|
configure: (proxy, options) => { |
|
// proxy will be an instance of 'http-proxy' |
|
}, |
|
}, |
|
// Proxying websockets or socket.io: |
|
// ws://localhost:5173/socket.io |
|
// -> ws://localhost:5174/socket.io |
|
// Exercise caution using `rewriteWsOrigin` as it can leave the |
|
// proxying open to CSRF attacks. |
|
'/socket.io': { |
|
target: 'ws://localhost:5174', |
|
ws: true, |
|
rewriteWsOrigin: true, |
|
}, |
|
}, |
|
}, |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Spin up a Vite-powered app |
|
DESCRIPTION: Command to quickly create a new Vite project. Requires Node.js version 12 or higher. |
|
|
|
SOURCE: https://vite.dev/blog/announcing-vite2 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm init @vitejs/app |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite Build and Preview Scripts |
|
DESCRIPTION: Defines npm scripts for building a Vite application (`vite build`) and previewing the production build locally (`vite preview`). These are essential for managing the build and deployment process. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: json |
|
CODE: |
|
``` |
|
{ |
|
"scripts": { |
|
"build": "vite build", |
|
"preview": "vite preview" |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Patching Dependencies for Strict Mode Issues |
|
DESCRIPTION: When encountering errors related to strict mode in dependencies (e.g., `with` statements), you can use patching tools like `patch-package`, `yarn patch`, or `pnpm patch` to modify the dependency code. This acts as an escape hatch for incompatible code. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm install patch-package postinstall-postinstall |
|
|
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npx patch-package <package-name> |
|
|
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
yarn patch <package-name> |
|
|
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm patch <package-name> |
|
|
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite build.lib Configuration |
|
DESCRIPTION: Configures Vite to build the project as a library. It allows specifying entry points, library name, output formats, and file names for JavaScript and CSS. |
|
|
|
SOURCE: https://vite.dev/config/build-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
build.lib: |
|
Type: { entry: string | string[] | { [entryAlias: string]: string }, name?: string, formats?: ('es' | 'cjs' | 'umd' | 'iife')[], fileName?: string | ((format: ModuleFormat, entryName: string) => string), cssFileName?: string } |
|
Related: [Library Mode](/guide/build#library-mode) |
|
Description: Build as a library. `entry` is required since the library cannot use HTML as entry. `name` is the exposed global variable and is required when `formats` includes 'umd' or 'iife'. Default `formats` are ['es', 'umd'], or ['es', 'cjs'], if multiple entries are used. |
|
|
|
`fileName` is the name of the package file output, which defaults to the "name" in `package.json`. It can also be defined as a function taking the `format` and `entryName` as arguments, and returning the file name. |
|
|
|
If your package imports CSS, `cssFileName` can be used to specify the name of the CSS file output. It defaults to the same value as `fileName` if it's set a string, otherwise it also falls back to the "name" in `package.json`. |
|
``` |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { |
|
defineConfig |
|
} from 'vite' |
|
|
|
export default |
|
defineConfig |
|
({ |
|
build: { |
|
lib: { |
|
entry: ['src/main.js'], |
|
fileName: ( |
|
format, |
|
entryName |
|
) => `my-lib-${ |
|
entryName |
|
}.${ |
|
format |
|
}.js`, |
|
cssFileName: 'my-lib-style' |
|
} |
|
} |
|
}) |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Node.js Conditional Exports Example |
|
DESCRIPTION: Illustrates the `exports` field in `package.json` and how Vite's `resolve.conditions` option interacts with it. Conditional exports allow packages to specify different entry points based on environment or module type (e.g., 'import', 'require'). |
|
|
|
SOURCE: https://vite.dev/config/shared-options |
|
|
|
LANGUAGE: json |
|
CODE: |
|
``` |
|
{ |
|
"exports": { |
|
".": { |
|
"import": "./index.mjs", |
|
"require": "./index.js" |
|
} |
|
} |
|
} |
|
``` |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
resolve.conditions: |
|
Type: string[] |
|
Default: ['module', 'browser', 'development|production'] |
|
Description: Additional conditions for resolving Conditional Exports from packages. The `development|production` value is dynamically replaced based on `process.env.NODE_ENV`. 'import', 'require', and 'default' conditions are always applied if met. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite: Create and Use FetchableDevEnvironment |
|
DESCRIPTION: Demonstrates creating a Vite server with a custom `FetchableDevEnvironment` that handles requests via the Fetch API. It shows importing necessary functions, configuring the environment, and dispatching a fetch request. The environment requires `Request` and `Response` instances for `dispatchFetch`, and Vite will validate these types. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-frameworks |
|
|
|
LANGUAGE: typescript |
|
CODE: |
|
``` |
|
import { |
|
createServer, |
|
createFetchableDevEnvironment, |
|
isFetchableDevEnvironment, |
|
} from 'vite' |
|
|
|
const server = await createServer({ |
|
server: { middlewareMode: true }, |
|
appType: 'custom', |
|
environments: { |
|
custom: { |
|
dev: { |
|
createEnvironment(name, config) { |
|
return createFetchableDevEnvironment(name, config, { |
|
handleRequest(request: Request): Promise<Response> | Response { |
|
// handle Request and return a Response |
|
}, |
|
}) |
|
}, |
|
}, |
|
}, |
|
}, |
|
}) |
|
|
|
// Any consumer of the environment API can now call `dispatchFetch` |
|
if (isFetchableDevEnvironment(server.environments.custom)) { |
|
const response: Response = await server.environments.custom.dispatchFetch( |
|
new Request('/request-to-handle'), |
|
) |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Build Vite Application |
|
DESCRIPTION: Executes the Vite build command to generate production-ready static assets. The output is typically placed in the 'dist' directory, ready for deployment. |
|
|
|
SOURCE: https://vite.dev/guide/static-deploy |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
$ npm run build |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite SSR: Run Entrypoint in Custom Dev Environment |
|
DESCRIPTION: Demonstrates setting up a Vite development server with a plugin to handle virtual modules. It shows how to interact with a custom SSR environment, specifically checking for `CustomDevEnvironment` and running an entrypoint module. |
|
|
|
SOURCE: https://vite.dev/guide/api-environment-frameworks |
|
|
|
LANGUAGE: ts |
|
CODE: |
|
``` |
|
import { createServer } from 'vite' |
|
|
|
const server = createServer({ |
|
plugins: [ |
|
// a plugin that handles `virtual:entrypoint` |
|
{ |
|
name: 'virtual-module', |
|
/* plugin implementation */ |
|
}, |
|
], |
|
}) |
|
const ssrEnvironment = server.environment.ssr |
|
const input = {} |
|
|
|
// use exposed functions by each environment factories that runs the code |
|
// check for each environment factories what they provide |
|
if (ssrEnvironment instanceof CustomDevEnvironment) { |
|
ssrEnvironment.runEntrypoint('virtual:entrypoint') |
|
} else { |
|
throw new Error(`Unsupported runtime for ${ssrEnvironment.name}`) |
|
} |
|
|
|
// ------------------------------------- |
|
// virtual:entrypoint |
|
const { createHandler } = await import('./entrypoint.js') |
|
const handler = createHandler(input) |
|
const response = handler(new Request('/')) |
|
|
|
// ------------------------------------- |
|
// ./entrypoint.js |
|
export function createHandler(input) { |
|
return function handler(req) { |
|
return new Response('hello') |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite `importedChunks` Pseudo Implementation (TypeScript) |
|
DESCRIPTION: A pseudo-implementation in TypeScript for a function that resolves all imported chunks recursively starting from a given entry point name. This function helps in identifying all CSS and JavaScript files needed for a specific entry point, which is crucial for generating the correct HTML tags. |
|
|
|
SOURCE: https://vite.dev/guide/backend-integration |
|
|
|
LANGUAGE: typescript |
|
CODE: |
|
``` |
|
import type { Manifest, ManifestChunk } from 'vite' |
|
|
|
export default function importedChunks( |
|
manifest: Manifest, |
|
name: string, |
|
): ManifestChunk[] { |
|
const seen = new Set<string>() |
|
|
|
function getImportedChunks(chunk: ManifestChunk): ManifestChunk[] { |
|
const chunks: ManifestChunk[] = [] |
|
for (const file of chunk.imports ?? []) { |
|
const importee = manifest[file] |
|
if (seen.has(file)) { |
|
continue |
|
} |
|
seen.add(file) |
|
|
|
chunks.push(...getImportedChunks(importee)) |
|
chunks.push(importee) |
|
} |
|
|
|
return chunks |
|
} |
|
|
|
return getImportedChunks(manifest[name]) |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: HMR Case Sensitivity Issue |
|
DESCRIPTION: Addresses Hot Module Replacement (HMR) failures when importing files with incorrect casing. Vite's HMR might not update if the imported file name casing differs from the actual file name. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
// Incorrect import (e.g., src/foo.js exists, but imported as Foo.js) |
|
import './Foo.js' |
|
|
|
// Correct import |
|
// import './foo.js' |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite build.ssr Option |
|
DESCRIPTION: Configures Vite to produce an SSR-oriented build. The entry point for SSR can be specified directly or via rollupOptions.input. |
|
|
|
SOURCE: https://vite.dev/config/build-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
build.ssr: |
|
Type: boolean | string |
|
Default: false |
|
Related: [Server-Side Rendering](/guide/ssr) |
|
Description: Produce SSR-oriented build. The value can be a string to directly specify the SSR entry, or `true`, which requires specifying the SSR entry via `rollupOptions.input`. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite optimizeDeps.holdUntilCrawlEnd Configuration |
|
DESCRIPTION: An experimental option that, when enabled (defaulting to true), delays the release of the first optimized dependency results until all static imports have been crawled on a cold start. This prevents full-page reloads caused by newly discovered dependencies generating new common chunks. Disabling this can allow the browser to process more requests in parallel if all dependencies are found early. |
|
|
|
SOURCE: https://vite.dev/config/dep-optimization-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
optimizeDeps.holdUntilCrawlEnd |
|
Type: boolean |
|
Default: true |
|
Experimental: Yes |
|
Description: When enabled, it will hold the first optimized deps results until all static imports are crawled on cold start. This avoids the need for full-page reloads when new dependencies are discovered and they trigger the generation of new common chunks. If all dependencies are found by the scanner plus the explicitly defined ones in `include`, it is better to disable this option to let the browser process more requests in parallel. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Vite optimizeDeps.needsInterop Configuration |
|
DESCRIPTION: An experimental option to force ESM interop for specific dependencies. Vite typically detects the need for interop automatically, but this array can be used to manually specify packages that require it, potentially speeding up cold starts by avoiding full-page reloads. A warning will be issued if Vite detects a dependency might benefit from being added to this list. |
|
|
|
SOURCE: https://vite.dev/config/dep-optimization-options |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
optimizeDeps.needsInterop |
|
Type: string[] |
|
Experimental: Yes |
|
Description: Forces ESM interop when importing these dependencies. Vite is able to properly detect when a dependency needs interop, so this option isn't generally needed. However, different combinations of dependencies could cause some of them to be prebundled differently. Adding these packages to `needsInterop` can speed up cold start by avoiding full-page reloads. You'll receive a warning if this is the case for one of your dependencies, suggesting to add the package name to this array in your config. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Adjust Max HTTP Header Size |
|
DESCRIPTION: Mitigates '431 Request Header Fields Too Large' errors in Node.js by allowing adjustment of the maximum HTTP header size. This can be done via a CLI flag or by reducing header content like cookies. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: shell |
|
CODE: |
|
``` |
|
# Example of changing max header size via CLI flag: |
|
# vite --max-http-header-size=8000 |
|
|
|
# Alternatively, reduce header size by removing large cookies or other data. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Force Re-optimization of Dependencies |
|
DESCRIPTION: When linking local packages or making changes that Vite's dependency optimization might miss, you can force Vite to re-optimize dependencies. This is often necessary after using `npm link` or similar tools. Using `vite --force` triggers a full re-optimization. |
|
|
|
SOURCE: https://vite.dev/guide/troubleshooting |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
vite --force |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: ViteDevServer Interface |
|
DESCRIPTION: The ViteDevServer interface defines the core object for the Vite development server. It exposes properties for accessing the Vite configuration, Connect middleware, Node.js http server, file watcher, WebSocket server, plugin container, module graph, and resolved URLs. It also includes methods for programmatically transforming requests, transforming HTML, loading modules for SSR, fixing stack traces, reloading modules, starting, restarting, and closing the server, and binding CLI shortcuts. The `waitForRequestsIdle` method is an experimental feature to wait for static imports to be processed. |
|
|
|
SOURCE: https://vite.dev/guide/api-javascript |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
ViteDevServer: |
|
config: ResolvedConfig |
|
- The resolved Vite config object. |
|
middlewares: Connect.Server |
|
- A connect app instance. |
|
- Can be used to attach custom middlewares to the dev server. |
|
- Can also be used as the handler function of a custom http server or as a middleware in any connect-style Node.js frameworks. |
|
- https://github.com/senchalabs/connect#use-middleware |
|
httpServer: http.Server | null |
|
- Native Node http server instance. |
|
- Will be null in middleware mode. |
|
watcher: FSWatcher |
|
- Chokidar watcher instance. If `config.server.watch` is set to `null`, it will not watch any files and calling `add` or `unwatch` will have no effect. |
|
- https://github.com/paulmillr/chokidar/tree/3.6.0#api |
|
ws: WebSocketServer |
|
- Web socket server with `send(payload)` method. |
|
pluginContainer: PluginContainer |
|
- Rollup plugin container that can run plugin hooks on a given file. |
|
moduleGraph: ModuleGraph |
|
- Module graph that tracks the import relationships, url to file mapping and hmr state. |
|
resolvedUrls: ResolvedServerUrls | null |
|
- The resolved urls Vite prints on the CLI (URL-encoded). Returns `null` in middleware mode or if the server is not listening on any port. |
|
transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null> |
|
- Programmatically resolve, load and transform a URL and get the result without going through the http request pipeline. |
|
transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string> |
|
- Apply Vite built-in HTML transforms and any plugin HTML transforms. |
|
ssrLoadModule(url: string, options?: { fixStacktrace?: boolean }): Promise<Record<string, any>> |
|
- Load a given URL as an instantiated module for SSR. |
|
ssrFixStacktrace(e: Error): void |
|
- Fix ssr error stacktrace. |
|
reloadModule(module: ModuleNode): Promise<void> |
|
- Triggers HMR for a module in the module graph. You can use the `server.moduleGraph` API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op. |
|
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer> |
|
- Start the server. |
|
restart(forceOptimize?: boolean): Promise<void> |
|
- Restart the server. |
|
- @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag |
|
close(): Promise<void> |
|
- Stop the server. |
|
bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void |
|
- Bind CLI shortcuts |
|
waitForRequestsIdle: (ignoredId?: string) => Promise<void> |
|
- Calling `await server.waitForRequestsIdle(id)` will wait until all static imports are processed. If called from a load or transform plugin hook, the id needs to be passed as a parameter to avoid deadlocks. Calling this function after the first static imports section of the module graph has been processed will resolve immediately. |
|
- @experimental |
|
- INFO: `waitForRequestsIdle` is meant to be used as a escape hatch to improve DX for features that can't be implemented following the on-demand nature of the Vite dev server. It can be used during startup by tools like Tailwind to delay generating the app CSS classes until the app code has been seen, avoiding flashes of style changes. When this function is used in a load or transform hook, and the default HTTP1 server is used, one of the six http channels will be blocked until the server processes all static imports. Vite's dependency optimizer currently uses this function to avoid full-page reloads on missing dependencies by delaying loading of pre-bundled dependencies until all imported dependencies have been collected from static imported sources. Vite may switch to a different strategy in a future major release, setting `optimizeDeps.crawlUntilStaticImports: false` by default to avoid the performance hit in large applications during cold start. |
|
``` |