new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vite · Guide · all subjects

javascript api

56 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

ViteDevServer.close method

ViteDevServer.close(): Promise<void> stops the server.

ViteDevServer.bindCLIShortcuts method

ViteDevServer.bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void binds CLI shortcuts.

loadEnv default behavior

By default, loadEnv only loads env variables prefixed with VITE_, unless prefixes is changed.

normalizePath function signature

The normalizePath function has the type signature: function normalizePath(id: string): string. It normalizes a path to interoperate between Vite plugins.

createServer function signature

The createServer function has the type signature: async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>. It accepts an optional InlineConfig object and returns a Promise that resolves to a ViteDevServer.

createServer basic usage example

import { createServer } from 'vite' const server = await createServer({ configFile: false, root: import.meta.dirname, server: { port: 1337, }, }) await server.listen() server.printUrls() server.bindCLIShortcuts({ print: true })

createServer process.env.NODE_ENV conflict prevention

When using createServer and build in the same Node.js process, both functions rely on process.env.NODE_ENV to work properly, which also depends on the mode config option. To prevent conflicting behavior, set process.env.NODE_ENV or the mode of the two APIs to development. Otherwise, spawn a child process to run the APIs separately.

createServer with middleware mode and WebSocket proxy

When using middleware mode combined with proxy config for WebSocket, the parent http server should be provided in middlewareMode to bind the proxy correctly. Example: import http from 'http' import { createServer } from 'vite' const parentServer = http.createServer() const vite = await createServer({ server: { middlewareMode: { server: parentServer, }, proxy: { '/ws': { target: 'ws://localhost:3000', ws: true, }, }, }, }) parentServer.use(vite.middlewares)

InlineConfig configFile property

The InlineConfig interface has a configFile property that specifies which config file to use. If not set, Vite will try to automatically resolve one from project root. Set to false to disable auto resolving.

ResolvedConfig properties and utilities

ResolvedConfig contains all the same properties of UserConfig, except most properties are resolved and non-undefined. It also contains utilities: config.assetsInclude (a function to check if an id is considered an asset) and config.logger (Vite's internal logger object).

ViteDevServer.config property

ViteDevServer.config is the resolved Vite config object of type ResolvedConfig.

ViteDevServer.middlewares property

ViteDevServer.middlewares is a Connect.Server instance that can be used to attach custom middlewares to the dev server or as the handler function of a custom http server or as middleware in connect-style Node.js frameworks. See https://github.com/senchalabs/connect#use-middleware

ViteDevServer.httpServer property

ViteDevServer.httpServer is the native Node http.Server instance. It will be null in middleware mode.

ViteDevServer.watcher property

ViteDevServer.watcher is a 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. See https://github.com/paulmillr/chokidar/tree/3.6.0#api

ViteDevServer.ws property

ViteDevServer.ws is a WebSocket server with a send(payload) method.

ViteDevServer.pluginContainer property

ViteDevServer.pluginContainer is a Rollup plugin container that can run plugin hooks on a given file.

ViteDevServer.moduleGraph property

ViteDevServer.moduleGraph is a module graph that tracks the import relationships, url to file mapping, and hmr state.

ViteDevServer.resolvedUrls property

ViteDevServer.resolvedUrls contains 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.

ViteDevServer.transformRequest method

ViteDevServer.transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null> programmatically resolves, loads and transforms a URL and gets the result without going through the http request pipeline.

ViteDevServer.transformIndexHtml method

ViteDevServer.transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string> applies Vite built-in HTML transforms and any plugin HTML transforms.

ViteDevServer.ssrLoadModule method

ViteDevServer.ssrLoadModule(url: string, options?: { fixStacktrace?: boolean }): Promise<Record<string, any>> loads a given URL as an instantiated module for SSR.

ViteDevServer.ssrFixStacktrace method

ViteDevServer.ssrFixStacktrace(e: Error): void fixes ssr error stacktrace.

ViteDevServer.reloadModule method

ViteDevServer.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.

ViteDevServer.listen method

ViteDevServer.listen(port?: number, isRestart?: boolean): Promise<ViteDevServer> starts the server and returns a Promise resolving to ViteDevServer.

ViteDevServer.restart method

ViteDevServer.restart(forceOptimize?: boolean): Promise<void> restarts the server. The forceOptimize parameter forces the optimizer to re-bundle, same as the --force CLI flag.

ViteDevServer.waitForRequestsIdle method

ViteDevServer.waitForRequestsIdle: (ignoredId?: string) => Promise<void> waits 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. This is marked as experimental.

waitForRequestsIdle use cases

waitForRequestsIdle is meant to be used as an 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. Vite's dependency optimizer 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.

build function signature

The build function has the type signature: async function build(inlineConfig?: InlineConfig): Promise<RolldownOutput | RolldownOutput[] | RolldownWatcher>. It accepts an optional InlineConfig object and returns a Promise that resolves to RolldownOutput, an array of RolldownOutput, or RolldownWatcher.

build function usage example

import path from 'node:path' import { build } from 'vite' await build({ root: path.resolve(import.meta.dirname, './project'), base: '/foo/', build: { rolldownOptions: { // ... }, }, })

preview function signature

The preview function has the type signature: async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>. It accepts an optional InlineConfig object and returns a Promise that resolves to a PreviewServer.

preview function usage example

import { preview } from 'vite' const previewServer = await preview({ preview: { port: 8080, open: true, }, }) previewServer.printUrls() previewServer.bindCLIShortcuts({ print: true })

PreviewServer.config property

PreviewServer.config is the resolved vite config object of type ResolvedConfig.

PreviewServer.middlewares property

PreviewServer.middlewares is a Connect.Server instance that can be used to attach custom middlewares to the preview server or as the handler function of a custom http server or as middleware in connect-style Node.js frameworks. See https://github.com/senchalabs/connect#use-middleware

PreviewServer.httpServer property

PreviewServer.httpServer is the native Node http.Server instance.

PreviewServer.resolvedUrls property

PreviewServer.resolvedUrls contains the resolved urls Vite prints on the CLI (URL-encoded). Returns null if the server is not listening on any port.

PreviewServer.printUrls method

PreviewServer.printUrls(): void prints the server URLs.

PreviewServer.bindCLIShortcuts method

PreviewServer.bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void binds CLI shortcuts.

resolveConfig function signature

The resolveConfig function has the type signature: async function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode = 'development', defaultNodeEnv = 'development', isPreview = false): Promise<ResolvedConfig>. The command value is 'serve' in dev and preview, and 'build' in build.

mergeConfig function signature

The mergeConfig function has the type signature: function mergeConfig(defaults: Record<string, any>, overrides: Record<string, any>, isRoot = true): Record<string, any>. It deeply merges two Vite configs. isRoot represents the level within the Vite config which is being merged. For example, set false if merging two build options.

mergeConfig null and undefined handling

In mergeConfig, null and undefined values in overrides are skipped and not merged. If you need to explicitly clear a value from defaults, modify the result of mergeConfig directly.

mergeConfig with callback form config

mergeConfig accepts only config in object form. If you have a config in callback form, you should call it before passing into mergeConfig. You can use the defineConfig helper to merge a config in callback form with another config: export default defineConfig((configEnv) => mergeConfig(configAsCallback(configEnv), configAsObject))

searchForWorkspaceRoot function signature

The searchForWorkspaceRoot function has the type signature: function searchForWorkspaceRoot(current: string, root = searchForPackageRoot(current)): string. It searches for the root of the potential workspace if it meets certain conditions, otherwise it would fallback to root.

searchForWorkspaceRoot detection criteria

searchForWorkspaceRoot detects a workspace root if the directory contains a workspaces field in package.json or contains one of the following files: lerna.json, pnpm-workspace.yaml.

loadEnv function signature

The loadEnv function has the type signature: function loadEnv(mode: string, envDir: string, prefixes: string | string[] = 'VITE_'): Record<string, string>. It loads .env files within the envDir and merges them with the matching variables already present in process.env.

transformWithOxc function signature

The transformWithOxc function has the type signature: async function transformWithOxc(code: string, filename: string, options?: OxcTransformOptions, inMap?: object): Promise<Omit<OxcTransformResult, 'errors'> & { warnings: string[] }>. It transforms JavaScript or TypeScript with Oxc Transformer. It is useful for plugins that prefer matching Vite's internal Oxc Transformer transform.

transformWithEsbuild function signature and deprecation

The transformWithEsbuild function has the type signature: async function transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise<ESBuildTransformResult>. It transforms JavaScript or TypeScript with esbuild. This function is deprecated; use transformWithOxc instead.

loadConfigFromFile function signature

The loadConfigFromFile function has the type signature: async function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot: string = process.cwd(), logLevel?: LogLevel, customLogger?: Logger): Promise<{ path: string, config: UserConfig, dependencies: string[] } | null>. It loads a Vite config file manually with Rolldown.

preprocessCSS function signature

The preprocessCSS function has the type signature: async function preprocessCSS(code: string, filename: string, config: ResolvedConfig): Promise<PreprocessCSSResult>. It pre-processes .css, .scss, .sass, .less, .styl and .stylus files to plain CSS so it can be used in browsers or parsed by other tools. This is marked as experimental.

PreprocessCSSResult interface

PreprocessCSSResult has the following properties: code (string), map (SourceMapInput, optional), modules (Record<string, string>, optional) for CSS modules mapping, and deps (Set<string>, optional) for dependencies.

preprocessCSS usage notes

In preprocessCSS, the pre-processor used is inferred from the filename extension. If the filename ends with .module.{ext}, it is inferred as a CSS module and the returned result will include a modules object mapping the original class names to the transformed ones. Pre-processing will not resolve URLs in url() or image-set().

version constant

The version constant is of type string and contains the current version of Vite as a string, for example '8.0.0'.

rolldownVersion constant

The rolldownVersion constant is of type string and contains the version of Rolldown used by Vite as a string, for example '1.0.0'. It is a re-export of VERSION from rolldown.

esbuildVersion constant kept for backward compatibility

The esbuildVersion constant is of type string and is only kept for backward compatibility.

rollupVersion constant kept for backward compatibility

The rollupVersion constant is of type string and is only kept for backward compatibility.

build() throws BundleError in JavaScript API

In Vite 8, the build() JavaScript API now throws a BundleError (typed as Error & { errors?: RolldownError[] }) instead of the raw error. Individual errors are wrapped in an errors array accessible via e.errors.

parseAst/parseAstAsync deprecated in favor of parseSync/parse

In Vite 8, parseAst and parseAstAsync functions are deprecated in favor of parseSync and parse functions which have more features.

Give your agent this brain