### Scaffold Project with Tiged
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Example of using tiged to create a local copy of a community template and run it.
```bash
npx tiged user/project my-project
cd my-project
npm install
npm run dev
```
--------------------------------
### Basic index.html
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
A simple HTML file for a Vite project.
```html
Hello Vite!
```
--------------------------------
### Install Vite CLI
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Commands to install Vite as a development dependency using various package managers.
```bash
$ npm install -D vite
```
```bash
$ yarn add -D vite
```
```bash
$ pnpm add -D vite
```
```bash
$ bun add -D vite
```
```bash
$ deno add -D npm:vite
```
--------------------------------
### Scaffolding Your First Vite Project
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Commands to scaffold a new Vite project using different package managers.
```bash
$ npm create vite@latest
```
```bash
$ yarn create vite
```
```bash
$ pnpm create vite
```
```bash
$ bun create vite
```
```bash
$ deno init --npm vite
```
--------------------------------
### Run Vite Dev Server
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Commands to start the Vite development server using various package managers.
```bash
$ npx vite
```
```bash
$ yarn vite
```
```bash
$ pnpm vite
```
```bash
$ bunx vite
```
```bash
$ deno run -A npm:vite
```
--------------------------------
### Example
Source: https://github.com/vitejs/vite/blob/main/docs/config/preview-options.md
Example configuration for setting server and preview ports.
```js
export default defineConfig({
server: {
port: 3030,
},
preview: {
port: 8080,
},
})
```
--------------------------------
### Create Vite Project
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Commands to scaffold a new Vite project using different package managers, with an example for a Vue template.
```bash
# npm 7+, extra double-dash is needed:
$ npm create vite@latest my-vue-app -- --template vue
```
```bash
$ yarn create vite my-vue-app --template vue
```
```bash
$ pnpm create vite my-vue-app --template vue
```
```bash
$ bun create vite my-vue-app --template vue
```
```bash
$ deno init --npm vite my-vue-app --template vue
```
--------------------------------
### Programmatic Vite Preview Server Example
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-javascript.md
Shows how to programmatically start a Vite preview server, configure its port and auto-opening, and interact with the `PreviewServer` instance to print URLs and bind CLI shortcuts.
```typescript
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 })
```
--------------------------------
### Build and link Vite locally
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Steps to clone the Vite repository, build it, and link it locally for development, requiring pnpm.
```bash
git clone https://github.com/vitejs/vite.git
cd vite
pnpm install
cd packages/vite
pnpm run build
pnpm link # use your preferred package manager for this step
```
--------------------------------
### Default npm Scripts
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Standard npm scripts for a Vite project in `package.json`.
```json
{
"scripts": {
"dev": "vite", // start dev server, aliases: `vite dev`, `vite serve`
"build": "vite build", // build for production
"preview": "vite preview" // locally preview production build
}
}
```
--------------------------------
### Example Barrel File
Source: https://github.com/vitejs/vite/blob/main/docs/guide/performance.md
An example of a barrel file re-exporting APIs from other files.
```js
export * from './color.js'
export * from './dom.js'
export * from './slash.js'
```
--------------------------------
### Configuring Server Warmup
Source: https://github.com/vitejs/vite/blob/main/docs/guide/performance.md
Example `vite.config.js` configuration to warm up frequently used client files, preventing request waterfalls.
```js
export default defineConfig({
server: {
warmup: {
clientFiles: [
'./src/components/BigComponent.vue',
'./src/utils/big-utils.js'
]
}
}
})
```
--------------------------------
### Install specific commit
Source: https://github.com/vitejs/vite/blob/main/docs/guide/index.md
Commands to install a specific unreleased commit of Vite using various package managers.
```bash
$ npm install -D https://pkg.pr.new/vite@SHA
```
```bash
$ yarn add -D https://pkg.pr.new/vite@SHA
```
```bash
$ pnpm add -D https://pkg.pr.new/vite@SHA
```
```bash
$ bun add -D https://pkg.pr.new/vite@SHA
```
--------------------------------
### Netlify CLI Installation
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Command to install the Netlify CLI globally.
```bash
npm install -g netlify-cli
```
--------------------------------
### Inspecting Transform Logs
Source: https://github.com/vitejs/vite/blob/main/docs/guide/performance.md
Example output from running `vite --debug transform` to identify frequently used files and their transformation times.
```bash
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
```
--------------------------------
### Install dependencies
Source: https://github.com/vitejs/vite/blob/main/packages/create-vite/template-qwik/README.md
Command to install project dependencies using npm, pnpm, or yarn.
```bash
$ npm install # or pnpm install or yarn install
```
--------------------------------
### Configure preview port
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Example of configuring the preview server's port in package.json.
```json
{
"scripts": {
"preview": "vite preview --port 8080"
}
}
```
--------------------------------
### listen(port, isRestart)
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-javascript.md
Start the server.
```APIDOC
## Method: listen(port?: number, isRestart?: boolean)
### Description
Start the server.
### Signature
listen(port?: number, isRestart?: boolean): Promise
### Parameters
- **port** (number) - Optional - The port number for the server to listen on.
- **isRestart** (boolean) - Optional - Indicates if the server is being restarted.
### Returns
Promise - A promise that resolves to the `ViteDevServer` instance once the server is listening.
```
--------------------------------
### CSS Styling Example
Source: https://github.com/vitejs/vite/blob/main/playground/worker/index.html
Example of basic CSS styling for paragraphs and a class.
```css
p { background: rgba(0, 0, 0, 0.1); }
.classname { color: green; }
```
--------------------------------
### Generate Types for Documentation Code Examples
Source: https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md
Run this command in Vite's root folder to generate types required for `twoslash` in documentation code examples.
```shell
pnpm run build
```
--------------------------------
### Vercel CLI Installation and Deployment
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Command to install the Vercel CLI globally and deploy an application.
```bash
npm i -g vercel
```
```bash
vercel
```
--------------------------------
### Install CSS Pre-processors
Source: https://github.com/vitejs/vite/blob/main/docs/guide/features.md
Install the corresponding pre-processor package for Sass, Less, or Stylus to enable their use in Vite projects.
```bash
# .scss and .sass
npm add -D sass-embedded # or sass
# .less
npm add -D less
# .styl and .stylus
npm add -D stylus
```
--------------------------------
### Entry file exports
Source: https://github.com/vitejs/vite/blob/main/docs/guide/build.md
Example of an entry file (`lib/main.js`) exporting components for library users.
```js
import Foo from './Foo.vue'
import Bar from './Bar.vue'
export { Foo, Bar }
```
--------------------------------
### Install Cloudflare Vite Plugin
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Command to install the Cloudflare Vite plugin as a development dependency.
```bash
npm install --save-dev @cloudflare/vite-plugin
```
--------------------------------
### Install esbuild for CSS Minification
Source: https://github.com/vitejs/vite/blob/main/docs/config/build-options.md
Install esbuild as a development dependency to use it for CSS minification when `build.cssMinify` is set to 'esbuild'.
```sh
npm add -D esbuild
```
--------------------------------
### Adding a Plugin
Source: https://github.com/vitejs/vite/blob/main/docs/guide/using-plugins.md
Command to install the @vitejs/plugin-legacy package.
```bash
$ npm add -D @vitejs/plugin-legacy
```
--------------------------------
### Multi-Page App Directory Structure
Source: https://github.com/vitejs/vite/blob/main/docs/guide/build.md
Example directory structure for a multi-page application.
```plaintext
├── package.json
├── vite.config.js
├── index.html
├── main.js
└── nested
├── index.html
└── nested.js
```
--------------------------------
### Configuring polyfill specifiers
Source: https://github.com/vitejs/vite/blob/main/packages/plugin-legacy/README.md
Example showing how to specify polyfills for both `polyfills` and `modernPolyfills` options.
```js
import legacy from '@vitejs/plugin-legacy'
export default {
plugins: [
legacy({
polyfills: ['es.promise.finally', 'es/map', 'es/set'],
modernPolyfills: ['es.promise.finally'],
}),
],
}
```
--------------------------------
### Vite Dev Server Usage
Source: https://github.com/vitejs/vite/blob/main/docs/guide/cli.md
Basic usage for starting the Vite development server.
```bash
vite [root]
```
--------------------------------
### Example HTML Output for 'views/foo.js' Entry Point
Source: https://github.com/vitejs/vite/blob/main/docs/guide/backend-integration.md
Shows the recommended HTML tags to include for the `views/foo.js` entry point in a production build, demonstrating stylesheet links, script module, and optional module preload.
```html
```
--------------------------------
### Example HTML Output for 'views/bar.js' Entry Point
Source: https://github.com/vitejs/vite/blob/main/docs/guide/backend-integration.md
Shows the recommended HTML tags to include for the `views/bar.js` entry point in a production build, demonstrating stylesheet links, script module, and optional module preload.
```html
```
--------------------------------
### preview
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-javascript.md
The `preview` function starts a local server to preview the built application. It accepts an optional inline configuration to customize the server behavior.
```APIDOC
## preview(inlineConfig?: InlineConfig)
### Description
The `preview` function starts a local server to preview the built application. It accepts an optional inline configuration to customize the server behavior.
### Method
function
### Parameters
#### Function Parameters
- **inlineConfig** (InlineConfig) - Optional - Configuration options for the preview server, including `mode` and `configFile`.
### Response
#### Success Response
- **Promise** - A promise that resolves to a `PreviewServer` instance.
```
--------------------------------
### Preview command
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Command to test the built application locally.
```bash
$ npm run preview
```
--------------------------------
### Express server setup
Source: https://github.com/vitejs/vite/blob/main/docs/guide/ssr.md
Example of setting up a Vite dev server in middleware mode with Express, disabling Vite's own HTML serving logic to allow the parent server to take control.
```js
import fs from 'node:fs'
import path from 'node:path'
import express from 'express'
import { createServer as createViteServer } from 'vite'
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()
```
--------------------------------
### Vite HTML Entry Point Example
Source: https://github.com/vitejs/vite/blob/main/docs/guide/features.md
This snippet demonstrates a basic HTML file structure in a Vite project, showing how assets like favicons, stylesheets, images, and JavaScript modules are referenced and processed.
```html
```
--------------------------------
### Install Terser
Source: https://github.com/vitejs/vite/blob/main/packages/plugin-legacy/README.md
Command to install Terser, which is required by plugin-legacy for minification.
```sh
npm add -D terser
```
--------------------------------
### Netlify CLI Site Initialization
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Command to create a new Netlify site using the CLI.
```bash
netlify init
```
--------------------------------
### Start Vite Documentation Development Server
Source: https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md
Execute this command in Vite's root folder to run the documentation site locally for development.
```shell
pnpm run docs
```
--------------------------------
### Build for production
Source: https://github.com/vitejs/vite/blob/main/packages/create-vite/template-qwik/README.md
Command to build the application for production.
```bash
npm run build
```
--------------------------------
### Build command
Source: https://github.com/vitejs/vite/blob/main/docs/guide/static-deploy.md
Command to build the application.
```bash
$ npm run build
```
--------------------------------
### Example .env file
Source: https://github.com/vitejs/vite/blob/main/docs/guide/env-and-mode.md
An example `.env` file showing a `VITE_` prefixed variable and a non-prefixed variable.
```env
VITE_SOME_KEY=123
DB_PASSWORD=foobar
```
--------------------------------
### Run development server
Source: https://github.com/vitejs/vite/blob/main/packages/create-vite/template-qwik/README.md
Command to run the application in development mode.
```bash
npm run dev
```
--------------------------------
### Install Minifiers for Vite Build
Source: https://github.com/vitejs/vite/blob/main/docs/config/build-options.md
Install `esbuild` or `terser` as development dependencies to use them as minifiers with Vite's `build.minify` option.
```sh
npm add -D esbuild
npm add -D terser
```
--------------------------------
### External Svelte Store Example
Source: https://github.com/vitejs/vite/blob/main/packages/create-vite/template-svelte/README.md
An example of a simple external Svelte store that can be used to retain state across HMR updates.
```js
// store.js
// An extremely simple external store
import { writable } from 'svelte/store'
export default writable(0)
```
--------------------------------
### Accessing Environments from the Server
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-environment-instances.md
Example demonstrating how to access client and SSR environments from a Vite dev server instance.
```js
// create the server, or get it from the configureServer hook
const server = await createServer(/* options */)
const clientEnvironment = server.environments.client
clientEnvironment.transformRequest(url)
console.log(server.environments.ssr.moduleGraph)
```
--------------------------------
### Dependency Notation and Example
Source: https://github.com/vitejs/vite/blob/main/playground/ssr/src/forked-deadlock/README.md
Defines the notation for module dependencies and waiting states, followed by an example illustrating a forked deadlock scenario.
```text
A -> B means: B is imported by A and B has A in its stack
A ... B means: A is waiting for B to ssrLoadModule()
H -> X ... Y
H -> X -> Y ... B
H -> A ... B
H -> A -> B ... X
```
--------------------------------
### Plugin-side Application Communication Example
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-environment-plugins.md
Example of a plugin communicating with application instances using `environment.hot.on` to listen for messages and `environment.hot.send` to broadcast messages.
```js
configureServer(server) {
server.environments.ssr.hot.on('my:greetings', (data, client) => {
// do something with the data,
// and optionally send a response to that application instance
client.send('my:foo:reply', `Hello from server! You said: ${data}`)
})
// broadcast a message to all application instances
server.environments.ssr.hot.send('my:foo', 'Hello from server!')
}
```
--------------------------------
### Prepare Local Environment for Release (pnpm)
Source: https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md
Updates the local repository, installs dependencies, and builds the project to ensure it's ready for a package release.
```bash
git pull
```
```bash
pnpm i
```
```bash
pnpm build
```
--------------------------------
### Custom Environment Instance Example
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-environment.md
An example demonstrating how to use `customEnvironment` from `vite-environment-provider` to define a custom SSR environment with specific build output directories.
```js
import { customEnvironment } from 'vite-environment-provider'
export default {
build: {
outDir: '/dist/client',
},
environments: {
ssr: customEnvironment({
build: {
outDir: '/dist/ssr',
},
}),
},
}
```
--------------------------------
### Vite build command output
Source: https://github.com/vitejs/vite/blob/main/docs/guide/build.md
Example output when running `vite build` in library mode, showing generated bundle files and their sizes.
```shell
$ vite build
building for production...
dist/my-lib.js 0.08 kB / gzip: 0.07 kB
dist/my-lib.umd.cjs 0.30 kB / gzip: 0.16 kB
```
--------------------------------
### Configure Vite to Open Specific Path on Server Start
Source: https://github.com/vitejs/vite/blob/main/docs/config/server-options.md
This configuration sets Vite to automatically open the browser to a specific path, '/docs/index.html', when the development server starts.
```js
export default defineConfig({
server: {
open: '/docs/index.html',
},
})
```
--------------------------------
### Install SWC Plugin for Decorator Lowering
Source: https://github.com/vitejs/vite/blob/main/docs/guide/migration.md
Install the necessary SWC plugin and core package to enable lowering of native decorators as a workaround for Oxc's current lack of support.
```bash
$ npm install -D @rollup/plugin-swc @swc/core
```
```bash
$ yarn add -D @rollup/plugin-swc @swc/core
```
```bash
$ pnpm add -D @rollup/plugin-swc @swc/core
```
```bash
$ bun add -D @rollup/plugin-swc @swc/core
```
```bash
$ deno add -D npm:@rollup/plugin-swc npm:@swc/core
```
--------------------------------
### Basic `experimental.renderBuiltUrl` usage
Source: https://github.com/vitejs/vite/blob/main/docs/guide/build.md
An example demonstrating how to use `experimental.renderBuiltUrl` to return a runtime expression for JavaScript host types or a relative path otherwise.
```ts
import type { UserConfig } from 'vite'
// prettier-ignore
const config: UserConfig = {
experimental: {
renderBuiltUrl(filename, { hostType }) {
if (hostType === 'js') {
return { runtime: `window.__toCdnUrl(${JSON.stringify(filename)})` }
} else {
return { relative: true }
}
},
},
}
```
--------------------------------
### Install Babel Plugin for Decorator Lowering
Source: https://github.com/vitejs/vite/blob/main/docs/guide/migration.md
Install the necessary Babel plugin and Rolldown Babel plugin to enable lowering of native decorators as a workaround for Oxc's current lack of support.
```bash
$ npm install -D @rolldown/plugin-babel @babel/plugin-proposal-decorators
```
```bash
$ yarn add -D @rolldown/plugin-babel @babel/plugin-proposal-decorators
```
```bash
$ pnpm add -D @rolldown/plugin-babel @babel/plugin-proposal-decorators
```
```bash
$ bun add -D @rolldown/plugin-babel @babel/plugin-proposal-decorators
```
```bash
$ deno add -D npm:@rolldown/plugin-babel npm:@babel/plugin-proposal-decorators
```
--------------------------------
### Manual DevEnvironment Communication with Virtual Module
Source: https://github.com/vitejs/vite/blob/main/docs/guide/api-environment-frameworks.md
This snippet demonstrates setting up manual communication with a `DevEnvironment` using a virtual module when the code runs in the same runtime as user modules. It shows how to create a Vite server, define a virtual entrypoint, and handle requests.
```ts
// code using the Vite's APIs
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('http://example.com/'))
// -------------------------------------
// ./entrypoint.js
export function createHandler(input) {
return function handler(req) {
return new Response('hello')
}
}
```
--------------------------------
### SSR Dependencies Example
Source: https://github.com/vitejs/vite/blob/main/playground/ssr-deps/index.html
Example demonstrating hydration scripts and dynamic module imports, including a specific case to disable pre-transform optimization to trigger a race condition for testing purposes.
```javascript
// hydration scripts import '@vitejs/test-css-lib' // Using dynamic import, so the module is transformed when browser actually // requests it. This essentially disables pre-transform optimization that's // crucial to trigger a race condition, covered by the test case introduced // in https://github.com/vitejs/vite/pull/11973 import('virtual:isomorphic-module').then(({ default: message }) => { document.querySelector('.isomorphic-module-browser').textContent = message })
```
--------------------------------
### Install Trusted SSL Certificate on macOS (Shell)
Source: https://github.com/vitejs/vite/blob/main/docs/guide/troubleshooting.md
Install a self-signed SSL certificate as trusted via the macOS command line to prevent network requests from stalling due to Chrome's caching behavior.
```shell
security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db your-cert.cer
```
--------------------------------
### Advanced `experimental.renderBuiltUrl` with asset types
Source: https://github.com/vitejs/vite/blob/main/docs/guide/build.md
An example showing how to define different base options for public files, JavaScript host IDs, and other assets using the `type` and `hostId` context parameters.
```ts
import type { UserConfig } from 'vite'
import path from 'node:path'
// prettier-ignore
const config: UserConfig = {
experimental: {
renderBuiltUrl(filename, { hostId, hostType, type }) {
if (type === 'public') {
return 'https://www.domain.com/' + filename
} else if (path.extname(hostId) === '.js') {
return {
runtime: `window.__assetsPath(${JSON.stringify(filename)})`
}
} else {
return 'https://cdn.domain.com/assets/' + filename
}
},
},
}
```
--------------------------------
### Example of Generated License Markdown Output
Source: https://github.com/vitejs/vite/blob/main/docs/guide/features.md
Shows the typical structure and content of the `.vite/license.md` file, listing bundled dependencies and their respective licenses.
```markdown
# Licenses
The app bundles dependencies which contain the following licenses:
## dep-1 - 1.2.3 (CC0-1.0)
CC0 1.0 Universal
...
## dep-2 - 4.5.6 (MIT)
MIT License
...
```
--------------------------------
### Usage
Source: https://github.com/vitejs/vite/blob/main/packages/plugin-legacy/README.md
Example of how to configure the @vitejs/plugin-legacy in vite.config.js.
```js
// vite.config.js
import legacy from '@vitejs/plugin-legacy'
export default {
plugins: [
legacy({
targets: ['defaults', 'not IE 11']
})
]
}
```
--------------------------------
### package.json with CSS export
Source: https://github.com/vitejs/vite/blob/main/docs/guide/build.md
Example `package.json` showing how to export a bundled CSS file for users to import, alongside JS modules.
```json
{
"name": "my-lib",
"type": "module",
"files": ["dist"],
"main": "./dist/my-lib.umd.cjs",
"module": "./dist/my-lib.js",
"exports": {
".": {
"import": "./dist/my-lib.js",
"require": "./dist/my-lib.umd.cjs"
},
"./style.css": "./dist/my-lib.css"
}
}
```