### Install Surge CLI Source: https://vite.dev/guide/static-deploy Install the Surge command-line interface globally to deploy static sites. ```bash npm i -g surge ``` -------------------------------- ### Install Netlify CLI Source: https://vite.dev/guide/static-deploy Install the Netlify command-line interface globally using npm to manage and deploy your sites. ```bash npm install -g netlify-cli ``` -------------------------------- ### Scaffold Project with Tiged Source: https://vite.dev/guide Clone a community template from GitHub using `tiged`, then install dependencies and start the development server. ```bash npx tiged user/project my-project cd my-project npm install npm run dev ``` -------------------------------- ### Install CSS pre-processors Source: https://vite.dev/guide/features Install the necessary pre-processor packages to enable support for Sass, Less, or Stylus files. ```bash # .scss and .sass npm add -D sass-embedded # or sass # .less npm add -D less # .styl and .stylus npm add -D stylus ``` -------------------------------- ### server.listen(port, isRestart) Source: https://vite.dev/guide/api-javascript Start the server. ```APIDOC ## `server.listen` ### 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. ### Return Value - (Promise) - A promise that resolves to the `ViteDevServer` instance once the server is listening. ``` -------------------------------- ### preview Source: https://vite.dev/guide/api-javascript Starts a preview server for the Vite project. ```APIDOC ## preview ### Description Asynchronously starts a preview server for the Vite project, allowing for custom configuration. It returns a `PreviewServer` instance. ### Method `async function preview(inlineConfig?: InlineConfig): Promise` ### Parameters #### Request Body - **inlineConfig** (InlineConfig) - Optional - An object containing any valid user config options, plus `mode` and `configFile` for the preview server. ### Request Example ```ts import { preview } from 'vite' const previewServer = await preview({ preview: { port: 8080, open: true, }, }) previewServer.printUrls() previewServer.bindCLIShortcuts({ print: true }) ``` ### Response #### Success Response (200) - **PreviewServer** (object) - An instance of the `PreviewServer` interface, providing access to server properties and methods. ```ts interface PreviewServer { config: ResolvedConfig middlewares: Connect.Server httpServer: http.Server resolvedUrls: ResolvedServerUrls | null printUrls(): void bindCLIShortcuts(options?: BindCLIShortcutsOptions): void } ``` ``` -------------------------------- ### Install Vercel CLI Globally Source: https://vite.dev/guide/static-deploy Install the Vercel command-line interface globally to enable direct deployment from your terminal. ```bash npm i -g vercel ``` -------------------------------- ### Build Output Example Source: https://vite.dev/guide/build The output generated after running the vite build command. ```text $ 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 ``` -------------------------------- ### Defining a Framework Plugin Preset Source: https://vite.dev/guide/api-plugin This example demonstrates how to create a plugin preset that returns an array of multiple plugins, useful for bundling complex framework integrations. ```js import frameworkRefresh from 'vite-plugin-framework-refresh' import frameworkDevtools from 'vite-plugin-framework-devtools' export default function framework(config) { return [frameworkRefresh(config), frameworkDevTools(config)] } ``` -------------------------------- ### Install Firebase Tools Source: https://vite.dev/guide/static-deploy Install the Firebase command-line tools globally using npm to manage Firebase projects. ```bash npm i -g firebase-tools ``` -------------------------------- ### Example License File Output Source: https://vite.dev/guide/features The format of the generated license file containing dependency information. ```md # 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 ... ``` -------------------------------- ### Start Node.js Inspector for Profiling Source: https://vite.dev/guide/troubleshooting Use the `--profile` flag with the Vite dev server or build command to start the Node.js inspector and generate a CPU profile for performance analysis. ```bash vite --profile --open ``` ```bash vite build --profile ``` -------------------------------- ### Initialize a New Vite Project Source: https://vite.dev/blog/announcing-vite2 Use this command to quickly scaffold a new Vite application. Ensure Node.js version 12 or higher is installed. ```bash npm init @vitejs/app ``` -------------------------------- ### Start Vite Dev Server Source: https://vite.dev/guide/cli Starts the Vite development server in the current directory or a specified root. `vite dev` and `vite serve` are aliases. ```bash vite [root] ``` -------------------------------- ### Example Vite Production Manifest File Source: https://vite.dev/guide/backend-integration An example of the `.vite/manifest.json` file generated after a production build, mapping source files to their compiled output and dependencies. ```json { "_shared-B7PI925R.js": { "file": "assets/shared-B7PI925R.js", "name": "shared", "css": ["assets/shared-ChJ_j-JJ.css"] }, "_shared-ChJ_j-JJ.css": { "file": "assets/shared-ChJ_j-JJ.css", "src": "_shared-ChJ_j-JJ.css" }, "logo.svg": { "file": "assets/logo-BuPIv-2h.svg", "src": "logo.svg" }, "baz.js": { "file": "assets/baz-B2H3sXNv.js", "name": "baz", "src": "baz.js", "isDynamicEntry": true }, "views/bar.js": { "file": "assets/bar-gkvgaI9m.js", "name": "bar", "src": "views/bar.js", "isEntry": true, "imports": ["_shared-B7PI925R.js"], "dynamicImports": ["baz.js"] }, "views/foo.js": { "file": "assets/foo-BRBmoGS9.js", "name": "foo", "src": "views/foo.js", "isEntry": true, "imports": ["_shared-B7PI925R.js"], "css": ["assets/foo-5UjPuW-k.css"] } } ``` -------------------------------- ### ModuleRunner Usage Example Source: https://vite.dev/guide/api-environment-runtimes Demonstrates how to instantiate a ModuleRunner with a custom transport and import an entry point. ```js import { ModuleRunner, ESModulesEvaluator, createNodeImportMeta, } from 'vite/module-runner' import { transport } from './rpc-implementation.js' const moduleRunner = new ModuleRunner( { transport, createImportMeta: createNodeImportMeta, // if the module runner runs in Node.js }, new ESModulesEvaluator(), ) await moduleRunner.import('/src/entry-point.js') ``` -------------------------------- ### Install esbuild for CSS Minification Source: https://vite.dev/config/build-options Install esbuild as a development dependency to use it for CSS minification when "build.cssMinify" is set to "'esbuild'". ```sh npm add -D esbuild ``` -------------------------------- ### Run Vite Development Server Source: https://vite.dev/guide Start the Vite development server using the appropriate command for your package manager. ```bash npx vite ``` ```bash yarn vite ``` ```bash pnpm vite ``` ```bash bunx vite ``` ```bash deno run -A npm:vite ``` -------------------------------- ### Install SWC Decorator Plugin with Deno Source: https://vite.dev/guide/migration Install the necessary SWC plugin for handling decorators using Deno. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ deno add -D npm:@rollup/plugin-swc npm:@swc/core ``` -------------------------------- ### Start Vite Preview Server Programmatically (TypeScript) Source: https://vite.dev/guide/api-javascript Use this snippet to programmatically start a Vite preview server, configuring options like the port and whether to open the browser automatically. ```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 }) ``` -------------------------------- ### Configure Dependency Optimization Strategy for Cold Starts Source: https://vite.dev/blog/announcing-vite5-1 Set this option to 'false' to switch to an alternative dependency optimization strategy that can help improve server cold start performance in larger projects. ```javascript optimizeDeps.holdUntilCrawlEnd: false ``` -------------------------------- ### Install SWC Decorator Plugin with Bun Source: https://vite.dev/guide/migration Install the necessary SWC plugin for handling decorators using Bun. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ bun add -D @rollup/plugin-swc @swc/core ``` -------------------------------- ### Implement custom environment instances Source: https://vite.dev/guide/api-environment Example of using a custom environment provider, such as for Cloudflare Workers, to define specific build directories. ```js import { customEnvironment } from 'vite-environment-provider' export default { build: { outDir: '/dist/client', }, environments: { ssr: customEnvironment({ build: { outDir: '/dist/ssr', }, }), }, } ``` -------------------------------- ### Initialize Vite Dev Server with Custom Config Source: https://vite.dev/guide/api-javascript Use `createServer` to programmatically start a Vite development server. Configure options like `configFile`, `root`, and `server.port` directly. Remember to call `listen()` to start the server and `printUrls()` to display access URLs. ```ts import { createServer } from 'vite' const server = await createServer({ // any valid user config options, plus `mode` and `configFile` configFile: false, root: import.meta.dirname, server: { port: 1337, }, }) await server.listen() server.printUrls() server.bindCLIShortcuts({ print: true }) ``` -------------------------------- ### Install Babel Decorator Plugin with Deno Source: https://vite.dev/guide/migration Install the necessary Babel plugin for handling decorators using Deno. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ deno add -D npm:@rolldown/plugin-babel npm:@babel/plugin-proposal-decorators ``` -------------------------------- ### Install SWC Decorator Plugin with npm Source: https://vite.dev/guide/migration Install the necessary SWC plugin for handling decorators using npm. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ npm install -D @rollup/plugin-swc @swc/core ``` -------------------------------- ### Build and Link Vite from Source Source: https://vite.dev/guide Clone the Vite repository, install dependencies, build the 'vite' package, and link it globally for local development. This process requires 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 ``` -------------------------------- ### Install Babel Decorator Plugin with Bun Source: https://vite.dev/guide/migration Install the necessary Babel plugin for handling decorators using Bun. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ bun add -D @rolldown/plugin-babel @babel/plugin-proposal-decorators ``` -------------------------------- ### Install Legacy Plugin Source: https://vite.dev/guide/using-plugins Command to add the official legacy browser support plugin to project dependencies. ```bash $ npm add -D @vitejs/plugin-legacy ``` -------------------------------- ### createServer Source: https://vite.dev/guide/api-javascript Programmatically starts a Vite development server. It accepts an optional `InlineConfig` object to customize server behavior, returning a `Promise` that resolves to a `ViteDevServer` instance. ```APIDOC ## `createServer` ### Description Programmatically starts a Vite development server. It accepts an optional `InlineConfig` object to customize server behavior, returning a `Promise` that resolves to a `ViteDevServer` instance. ### Type Signature ```ts async function createServer(inlineConfig?: InlineConfig): Promise ``` ### Parameters - **inlineConfig** (`InlineConfig`) - Optional - Configuration options for the server. This interface extends `UserConfig` and includes: - **configFile** (boolean | string) - Optional - Specifies the config file to use. If not set, Vite resolves one from the project root. Set to `false` to disable auto-resolving. ### Example Usage ```ts import { createServer } from 'vite' const server = await createServer({ // any valid user config options, plus `mode` and `configFile` configFile: false, root: import.meta.dirname, server: { port: 1337, }, }) await server.listen() server.printUrls() server.bindCLIShortcuts({ print: true }) ``` ```ts import http from 'http' import { createServer } from 'vite' const parentServer = http.createServer() // or express, koa, etc. const vite = await createServer({ server: { // Enable middleware mode middlewareMode: { // Provide the parent http server for proxy WebSocket server: parentServer, }, proxy: { '/ws': { target: 'ws://localhost:3000', // Proxying WebSocket ws: true, }, }, }, }) // @noErrors: 2339 parentServer.use(vite.middlewares) ``` ``` -------------------------------- ### Vite Manifest Dependency Graph Example Source: https://vite.dev/guide/backend-integration Illustrates the dependency relationships between different chunks and assets within a Vite production manifest using a DOT graph visualization. ```dot digraph manifest { rankdir=TB node [shape=box style="rounded,filled" fontname="Arial" fontsize=10 margin="0.2,0.1" fontcolor="${#3c3c43|#ffffff}" color="${#c2c2c4|#3c3f44}"] edge [color="${#67676c|#98989f}" fontname="Arial" fontsize=9 fontcolor="${#67676c|#98989f}"] bgcolor="transparent" foo [label="views/foo.js\n(entry)" fillcolor="${#e9eaff|#222541}"] bar [label="views/bar.js\n(entry)" fillcolor="${#e9eaff|#222541}"] shared [label="_shared-B7PI925R.js\n(common chunk)" fillcolor="${#f2ecfc|#2c273e}"] baz [label="baz.js\n(dynamic import)" fillcolor="${#fcf4dc|#38301a}"] foocss [label="foo.css" shape=ellipse fillcolor="${#fde4e8|#3a1d27}"] sharedcss [label="shared.css" shape=ellipse fillcolor="${#fde4e8|#3a1d27}"] logo [label="logo.svg\n(asset)" shape=ellipse fillcolor="${#def5ed|#15312d}"] foo -> shared [label="imports"] bar -> shared [label="imports"] bar -> baz [label="dynamicImports" style=dashed] foo -> foocss [label="css"] shared -> sharedcss [label="css"] } ``` -------------------------------- ### Vite production transformation example Source: https://vite.dev/guide/assets Internal representation of how Vite transforms dynamic URL patterns during the production build process. ```js 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 } ``` -------------------------------- ### Import and initialize WebAssembly module in JavaScript Source: https://vite.dev/blog/announcing-vite3 Import a WASM module using `?init` query and then call its `init()` function to get the instance. ```js import init from './example.wasm?init' init().then((instance) => { instance.exports.test() }) ``` -------------------------------- ### Initialize a New Netlify Site Source: https://vite.dev/guide/static-deploy Create a new Netlify site and link it to your local project using the Netlify CLI. ```bash netlify init ``` -------------------------------- ### Worker Thread Transport Setup Source: https://vite.dev/guide/api-environment-runtimes Example of setting up a ModuleRunnerTransport to communicate with a worker thread using `parentPort` for messages. ```js import { parentPort } from 'node:worker_threads' import { fileURLToPath } from 'node:url' import { ESModulesEvaluator, ModuleRunner, createNodeImportMeta, } 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, createImportMeta: createNodeImportMeta, }, new ESModulesEvaluator(), ) ``` ```js 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 client = { send(payload: HotPayload) { worker.postMessage(payload) }, } const workerHotChannel = { // Worker threads post messages are not exposed over the network, skip server.fs checks skipFsCheck: true, send: (data) => worker.postMessage(data), on: (event, handler) => { // client is already connected if (event === 'vite:client:connect') return if (event === 'vite:client:disconnect') { const listener = () => { handler(undefined, client) } handlerToWorkerListener.set(handler, listener) worker.on('exit', listener) return } const listener = (value) => { if (value.type === 'custom' && value.event === event) { handler(value.data, client) } } handlerToWorkerListener.set(handler, listener) worker.on('message', listener) }, off: (event, handler) => { if (event === 'vite:client:connect') return if (event === 'vite:client:disconnect') { const listener = handlerToWorkerListener.get(handler) if (listener) { worker.off('exit', listener) handlerToWorkerListener.delete(handler) } 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, }, }, }, }) ``` -------------------------------- ### Preview Built Vite Application Locally using npm Source: https://vite.dev/guide/static-deploy Runs the `preview` script to start a local static web server, serving the built application from the `dist` folder for local testing. ```bash $ npm run preview ``` -------------------------------- ### Install Vite CLI Manually Source: https://vite.dev/guide Install the Vite command-line interface as a development dependency in your project. ```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 ``` -------------------------------- ### Create a new Vite project with various package managers Source: https://vite.dev Use these commands to initialize a new Vite project using npm, Yarn, pnpm, Bun, or Deno's npm compatibility mode. ```bash $ npm create vite@latest ``` ```bash $ yarn create vite ``` ```bash $ pnpm create vite ``` ```bash $ bun create vite ``` ```bash $ deno init --npm vite ``` -------------------------------- ### Install Minifiers for Vite Build Source: https://vite.dev/config/build-options Install `esbuild` or `terser` as development dependencies when specifying them as the `build.minify` option in Vite. ```sh npm add -D esbuild ``` ```sh npm add -D terser ``` -------------------------------- ### Create Basic index.html File Source: https://vite.dev/guide A minimal `index.html` file serving as the entry point for a Vite application. ```html

Hello Vite!

``` -------------------------------- ### Install Cloudflare Vite Plugin Source: https://vite.dev/guide/static-deploy Install the Cloudflare Vite plugin as a development dependency to integrate Cloudflare Workers with your Vite project. ```bash $ npm install --save-dev @cloudflare/vite-plugin ``` -------------------------------- ### Example of Forwarded Unhandled Error Log Source: https://vite.dev/config/server-options An example of how an unhandled error from the browser is formatted and logged in the Vite server terminal when `server.forwardConsole` is enabled. ```log 1:18:38 AM [vite] (client) [Unhandled error] Error: this is test error > testError src/main.ts:20:8 18| 19| function testError() { 20| throw new Error('this is test error') | ^ 21| } 22| > HTMLButtonElement. src/main.ts:6:2 ``` -------------------------------- ### Configure Server Warmup for Client and SSR Files Source: https://vite.dev/config/server-options Example configuration for `server.warmup` to pre-transform and cache frequently used client and SSR files, improving initial page load performance. ```js export default defineConfig({ server: { warmup: { clientFiles: ['./src/components/*.vue', './src/utils/big-utils.js'], ssrFiles: ['./src/server/modules/*.js'], }, }, }) ``` -------------------------------- ### Render Build and Publish Configuration Source: https://vite.dev/guide/static-deploy Configure Render's static site service with the build command to install dependencies and build the project, and specify the directory containing the built static files. ```bash npm install && npm run build ``` ```text dist ``` -------------------------------- ### Install Unreleased Vite Commit with pkg.pr.new Source: https://vite.dev/guide Install a specific unreleased Vite commit using pkg.pr.new. Replace 'SHA' with a valid commit hash from the last month. ```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 ``` -------------------------------- ### Example License Metadata JSON Output Source: https://vite.dev/config/build-options This JSON structure illustrates the format of the generated license metadata file when `build.license` is configured to output JSON, providing details for each bundled dependency. ```json [ { "name": "dep-1", "version": "1.2.3", "identifier": "CC0-1.0", "text": "CC0 1.0 Universal\n\n..." }, { "name": "dep-2", "version": "4.5.6", "identifier": "MIT", "text": "MIT License\n\n..." } ] ``` -------------------------------- ### Configure Vite to Open Specific Path on Server Start (JavaScript) Source: https://vite.dev/config/server-options Use this configuration to automatically open a specific URL pathname in the browser when the development server starts. ```js export default defineConfig({ server: { open: '/docs/index.html', }, }) ``` -------------------------------- ### Install SWC Decorator Plugin with pnpm Source: https://vite.dev/guide/migration Install the necessary SWC plugin for handling decorators using pnpm. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ pnpm add -D @rollup/plugin-swc @swc/core ``` -------------------------------- ### Install SWC Decorator Plugin with Yarn Source: https://vite.dev/guide/migration Install the necessary SWC plugin for handling decorators using Yarn. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ yarn add -D @rollup/plugin-swc @swc/core ``` -------------------------------- ### Implement and use FetchableDevEnvironment Source: https://vite.dev/guide/api-environment-frameworks Configures a custom environment using createFetchableDevEnvironment and demonstrates how to dispatch requests using dispatchFetch. ```ts 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 { // 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('http://example.com/request-to-handle'), ) } ``` -------------------------------- ### server.bindCLIShortcuts(options) Source: https://vite.dev/guide/api-javascript Bind CLI shortcuts. ```APIDOC ## `server.bindCLIShortcuts` ### Description Bind CLI shortcuts. ### Signature `bindCLIShortcuts(options?: BindCLIShortcutsOptions): void` ### Parameters - **options** (BindCLIShortcutsOptions) - Optional - Options for configuring CLI shortcuts. ### Return Value - (void) - This function does not return a value. ``` -------------------------------- ### Install Babel Decorator Plugin with pnpm Source: https://vite.dev/guide/migration Install the necessary Babel plugin for handling decorators using pnpm. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ pnpm add -D @rolldown/plugin-babel @babel/plugin-proposal-decorators ``` -------------------------------- ### Building with a Custom Mode (Staging) Source: https://vite.dev/guide/env-and-mode Build your Vite application for a specific mode like 'staging' using the --mode flag. Ensure a corresponding .env.staging file exists. ```bash vite build --mode staging ``` -------------------------------- ### Deploy Static Site to Netlify Source: https://vite.dev/guide/static-deploy Deploy your static site to Netlify, optionally using the '--prod' flag for a production deployment. ```bash netlify deploy ``` ```bash netlify deploy --prod ``` -------------------------------- ### Install Babel Decorator Plugin with Yarn Source: https://vite.dev/guide/migration Install the necessary Babel plugin for handling decorators using Yarn. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ yarn add -D @rolldown/plugin-babel @babel/plugin-proposal-decorators ``` -------------------------------- ### Install Babel Decorator Plugin with npm Source: https://vite.dev/guide/migration Install the necessary Babel plugin for handling decorators using npm. This is part of the workaround for lowering native decorators when Oxc does not support them. ```bash $ npm install -D @rolldown/plugin-babel @babel/plugin-proposal-decorators ``` -------------------------------- ### Implementing SSR Middleware with Environment API Source: https://vite.dev/guide/api-environment-frameworks Demonstrates setting up a Vite server in middleware mode and using the environment runner to execute server-side entry points. ```js import fs from 'node:fs' import path from 'node:path' import { createServer } from 'vite' 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(import.meta.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(``, appHtml) // 6. Send the rendered HTML back. res.status(200).set({ 'Content-Type': 'text/html' }).end(html) }) ``` -------------------------------- ### Initialize a Vite RSC project Source: https://vite.dev/plugins Use this command to scaffold a minimal standalone React Server Components application. ```bash npm create vite@latest -- --template rsc ``` -------------------------------- ### Configure Multi-Page App Build Source: https://vite.dev/guide/build Specify multiple HTML files as entry points for a multi-page application build. Ensure correct path resolution, especially when a different root is specified. ```js import { dirname, resolve } from 'node:path' import { defineConfig } from 'vite' export default defineConfig({ build: { rolldownOptions: { input: { main: resolve(import.meta.dirname, 'index.html'), nested: resolve(import.meta.dirname, 'nested/index.html'), }, }, }, }) ``` -------------------------------- ### Vite Preview Command Usage Source: https://vite.dev/guide/cli Displays the basic usage for the `vite preview` command, used to locally preview a production build. Requires running `vite build` beforehand. ```bash vite preview [root] ``` -------------------------------- ### Configure Legacy Plugin Source: https://vite.dev/guide/using-plugins Example of registering the legacy plugin within the vite.config.js file. ```javascript import legacy from '@vitejs/plugin-legacy' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ legacy({ targets: ['defaults', 'not IE 11'], }), ], }) ``` -------------------------------- ### PreviewServer.bindCLIShortcuts Source: https://vite.dev/guide/api-javascript Binds CLI shortcuts to the preview server. ```APIDOC ## PreviewServer.bindCLIShortcuts ### Description This method, available on the `PreviewServer` instance, binds command-line interface shortcuts for interacting with the server. ### Method `bindCLIShortcuts(options?: BindCLIShortcutsOptions): void` ### Parameters #### Request Body - **options** (BindCLIShortcutsOptions) - Optional - Options to configure the CLI shortcuts. ### Request Example ```ts previewServer.bindCLIShortcuts({ print: true }) ``` ### Response #### Success Response (200) - (void) - This method does not return any value. ``` -------------------------------- ### Configure Vite Build and Preview Scripts in package.json Source: https://vite.dev/guide/static-deploy Sets up `build` and `preview` npm scripts for a Vite project. The `build` script compiles the application, and `preview` serves the built output locally. ```json { "scripts": { "build": "vite build", "preview": "vite preview" } } ```