Skip to main content
Vite’s JavaScript APIs are fully typed, and it’s recommended to use TypeScript or enable JS type checking in VS Code to leverage the intellisense and validation.

createServer

Create a Vite development server instance programmatically. Type Signature:
async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>

Parameters

inlineConfig
InlineConfig
Configuration object that extends UserConfig with additional properties:

Returns

server
ViteDevServer
A promise that resolves to a ViteDevServer instance

Example Usage

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 })
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, you can spawn a child process to run the APIs separately.

Middleware Mode Example

When using middleware mode combined with proxy config for WebSocket, the parent http server should be provided in middlewareMode to bind the proxy correctly.

ViteDevServer

The ViteDevServer interface provides methods and properties for controlling the dev server.
interface ViteDevServer {
  config: ResolvedConfig
  middlewares: Connect.Server
  httpServer: http.Server | null
  watcher: FSWatcher
  ws: WebSocketServer
  pluginContainer: PluginContainer
  moduleGraph: ModuleGraph
  resolvedUrls: ResolvedServerUrls | null
  transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>
  transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>
  ssrLoadModule(url: string, options?: { fixStacktrace?: boolean }): Promise<Record<string, any>>
  ssrFixStacktrace(e: Error): void
  reloadModule(module: ModuleNode): Promise<void>
  listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
  restart(forceOptimize?: boolean): Promise<void>
  close(): Promise<void>
  bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void
  waitForRequestsIdle: (ignoredId?: string) => Promise<void>
  printUrls(): void
}

Properties

config
ResolvedConfig
The resolved Vite config object
middlewares
Connect.Server
A connect app instance that can be used to attach custom middlewares to the dev server or as the handler function of a custom http server
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.
ws
WebSocketServer
WebSocket 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.

Methods

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. The forceOptimize parameter forces 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>
Experimental - 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.
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. When used in a load or transform hook with the default HTTP1 server, one of the six http channels will be blocked until the server processes all static imports.

build

Build for production programmatically. Type Signature:
async function build(
  inlineConfig?: InlineConfig,
): Promise<RollupOutput | RollupOutput[]>

Parameters

inlineConfig
InlineConfig
Configuration object that extends UserConfig with additional properties like mode and configFile

Returns

output
RollupOutput | RollupOutput[]
Returns a Rollup output object or array of outputs

Example Usage

import path from 'node:path'
import { build } from 'vite'

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

preview

Create a Vite preview server to serve the built application. Type Signature:
async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>

Parameters

inlineConfig
InlineConfig
Configuration object with preview-specific options

Returns

previewServer
PreviewServer
A promise that resolves to a PreviewServer instance

Example Usage

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 })

PreviewServer

The PreviewServer interface for controlling the preview server.
interface PreviewServer {
  config: ResolvedConfig
  middlewares: Connect.Server
  httpServer: http.Server
  resolvedUrls: ResolvedServerUrls | null
  printUrls(): void
  bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void
}

Properties

config
ResolvedConfig
The resolved vite config object
middlewares
Connect.Server
A connect app instance that can be used to attach custom middlewares to the preview server
httpServer
http.Server
Native Node http server instance
resolvedUrls
ResolvedServerUrls | null
The resolved urls Vite prints on the CLI (URL-encoded). Returns null if the server is not listening on any port.

resolveConfig

Resolve the Vite configuration programmatically. Type Signature:
async function resolveConfig(
  inlineConfig: InlineConfig,
  command: 'build' | 'serve',
  defaultMode = 'development',
  defaultNodeEnv = 'development',
  isPreview = false,
): Promise<ResolvedConfig>

Parameters

inlineConfig
InlineConfig
required
Inline configuration object
command
'build' | 'serve'
required
The command value is serve in dev and preview, and build in build
defaultMode
string
default:"'development'"
Default mode to use if not specified
defaultNodeEnv
string
default:"'development'"
Default NODE_ENV to use if not specified
isPreview
boolean
default:"false"
Whether this is for preview mode

Returns

config
ResolvedConfig
The fully resolved Vite configuration

mergeConfig

Deeply merge two Vite configs. Type Signature:
function mergeConfig(
  defaults: Record<string, any>,
  overrides: Record<string, any>,
  isRoot = true,
): Record<string, any>

Parameters

defaults
Record<string, any>
required
The default configuration object
overrides
Record<string, any>
required
The override configuration object
isRoot
boolean
default:"true"
Represents the level within the Vite config which is being merged. Set to false if you’re merging two build options, for example.

Returns

merged
Record<string, any>
The merged configuration object
mergeConfig accepts only config in object form. If you have a config in callback form, you should call it before passing into mergeConfig.

Example with Callback Config

You can use the defineConfig helper to merge a config in callback form with another config:
import {
  defineConfig,
  mergeConfig,
  type UserConfigFnObject,
  type UserConfig,
} from 'vite'

declare const configAsCallback: UserConfigFnObject
declare const configAsObject: UserConfig

export default defineConfig((configEnv) =>
  mergeConfig(configAsCallback(configEnv), configAsObject),
)

searchForWorkspaceRoot

Search for the root of the potential workspace. Type Signature:
function searchForWorkspaceRoot(
  current: string,
  root = searchForPackageRoot(current),
): string

Parameters

current
string
required
Current directory to start searching from
root
string
Root directory to use as fallback

Returns

workspaceRoot
string
The workspace root directory path
Search for the root of the potential workspace if it meets the following conditions, otherwise it would fallback to root:
  • contains workspaces field in package.json
  • contains one of the following file:
    • lerna.json
    • pnpm-workspace.yaml

loadEnv

Load .env files from the environment directory. Type Signature:
function loadEnv(
  mode: string,
  envDir: string,
  prefixes: string | string[] = 'VITE_',
): Record<string, string>

Parameters

mode
string
required
The mode to load env files for (e.g., ‘development’, ‘production’)
envDir
string
required
The directory to load env files from
prefixes
string | string[]
default:"'VITE_'"
Only env variables prefixed with these values are loaded

Returns

env
Record<string, string>
An object containing the loaded environment variables
By default, only env variables prefixed with VITE_ are loaded, unless prefixes is changed.

normalizePath

Normalize a path to interoperate between Vite plugins. Type Signature:
function normalizePath(id: string): string

Parameters

id
string
required
The file path to normalize

Returns

normalizedPath
string
The normalized path with forward slashes

transformWithOxc

Transform JavaScript or TypeScript with Oxc Transformer. Type Signature:
async function transformWithOxc(
  code: string,
  filename: string,
  options?: OxcTransformOptions,
  inMap?: object,
): Promise<Omit<OxcTransformResult, 'errors'> & { warnings: string[] }>

Parameters

code
string
required
The source code to transform
filename
string
required
The filename for the code
options
OxcTransformOptions
Oxc transformer options
inMap
object
Input source map

Returns

result
OxcTransformResult & { warnings: string[] }
The transformed code with source map and warnings
Useful for plugins that prefer matching Vite’s internal Oxc Transformer transform.

transformWithEsbuild

Deprecated: Use transformWithOxc instead.
Transform JavaScript or TypeScript with esbuild. Type Signature:
async function transformWithEsbuild(
  code: string,
  filename: string,
  options?: EsbuildTransformOptions,
  inMap?: object,
): Promise<ESBuildTransformResult>
Useful for plugins that prefer matching Vite’s internal esbuild transform.

loadConfigFromFile

Load a Vite config file manually. 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>

Parameters

configEnv
ConfigEnv
required
Configuration environment with command and mode
configFile
string
Path to the config file to load
configRoot
string
default:"process.cwd()"
Root directory to search for config
logLevel
LogLevel
Logging level
customLogger
Logger
Custom logger instance

Returns

result
{ path: string, config: UserConfig, dependencies: string[] } | null
The loaded config with its path and dependencies, or null if not found

preprocessCSS

Experimental: Give Feedback
Pre-process CSS files to plain CSS. Type Signature:
async function preprocessCSS(
  code: string,
  filename: string,
  config: ResolvedConfig,
): Promise<PreprocessCSSResult>

interface PreprocessCSSResult {
  code: string
  map?: SourceMapInput
  modules?: Record<string, string>
  deps?: Set<string>
}

Parameters

code
string
required
The CSS source code
filename
string
required
The filename with extension (e.g., .scss, .less, .styl)
config
ResolvedConfig
required
The resolved Vite configuration

Returns

result
PreprocessCSSResult
The processed CSS with optional source map and CSS modules mapping
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. The pre-processor used is inferred from the filename extension.
The corresponding pre-processor must be installed if used. Pre-processing will not resolve URLs in url() or image-set().