JavaScript API
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
Type Signature:
async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>Example Usage:
import { createServerfunction createServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer> } from 'vite'
const serverconst server: ViteDevServer = await createServerfunction createServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer>({
// any valid user config options, plus `mode` and `configFile`
configFileconfigFile: false: false,
rootroot: string: import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
,
serverserver: {
port: number;
}
: {
portport: number: 1337,
},
})
await serverconst server: ViteDevServer.listenViteDevServer.listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>Start the server.
()
serverconst server: ViteDevServer.printUrlsViteDevServer.printUrls(): voidPrint server urls
()
serverconst server: ViteDevServer.bindCLIShortcutsViteDevServer.bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): voidBind CLI shortcuts
({ printprint?: boolean | undefinedPrint a one-line shortcuts "help" hint to the terminal
: true })NOTE
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.
NOTE
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 httpmodule "http"To use the HTTP server and client one must import the node:http module.
The HTTP interfaces in Node.js are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
user is able to stream data.
HTTP message headers are represented by an object like this:
{ "content-length": "123",
"content-type": "text/plain",
"connection": "keep-alive",
"host": "example.com",
"accept": "*" }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the Node.js
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.
See message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders property, which is an array of [key, value, key2, value2, ...]. For
example, the previous message header object might have a rawHeaders list like the following:
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'example.com',
'accepT', '*' ]
from 'http'
import { createServerfunction createServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer> } from 'vite'
const parentServerconst parentServer: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> = httpmodule "http"To use the HTTP server and client one must import the node:http module.
The HTTP interfaces in Node.js are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
user is able to stream data.
HTTP message headers are represented by an object like this:
{ "content-length": "123",
"content-type": "text/plain",
"connection": "keep-alive",
"host": "example.com",
"accept": "*" }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the Node.js
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.
See message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders property, which is an array of [key, value, key2, value2, ...]. For
example, the previous message header object might have a rawHeaders list like the following:
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'example.com',
'accepT', '*' ]
.createServerfunction createServer<typeof http.IncomingMessage, typeof http.ServerResponse>(requestListener?: http.RequestListener<typeof http.IncomingMessage, typeof http.ServerResponse> | undefined): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> (+1 overload)Returns a new instance of
Server
.
The requestListener is a function which is automatically
added to the 'request' event.
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer();
// Listen to the request event
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
() // or express, koa, etc.
const viteconst vite: ViteDevServer = await createServerfunction createServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer>({
serverserver: {
middlewareMode: {
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
};
proxy: {
'/ws': {
target: string;
ws: true;
};
};
}
: {
// Enable middleware mode
middlewareModemiddlewareMode: {
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
}
: {
// Provide the parent http server for proxy WebSocket
serverserver: HttpServerParent server instance to attach to
This is needed to proxy WebSocket connections to the parent server.
: parentServerconst parentServer: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
},
proxyproxy: {
'/ws': {
target: string;
ws: true;
};
}
: {
'/ws': {
targetServerOptions$3.target?: ProxyTarget | undefinedURL string to be parsed with the url module.
: 'ws://localhost:3000',
// Proxying WebSocket
wsServerOptions$3.ws?: boolean | undefinedIf you want to proxy websockets.
: true,
},
},
},
})
parentServerconst parentServer: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>.use(viteconst vite: ViteDevServer.middlewaresViteDevServer.middlewares: Connect.ServerA 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
)InlineConfig
The InlineConfig interface extends UserConfig with additional properties:
configFile: specify config file to use. If not set, Vite will try to automatically resolve one from project root. Set tofalseto disable auto resolving.
ResolvedConfig
The ResolvedConfig interface has all the same properties of a UserConfig, except most properties are resolved and non-undefined. It also contains utilities like:
config.assetsInclude: A function to check if anidis considered an asset.config.logger: Vite's internal logger object.
ViteDevServer
interface ViteDevServer {
/**
* The resolved Vite config object.
*/
config: ResolvedConfig
/**
* 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
*/
middlewares: Connect.Server
/**
* Native Node http server instance.
* Will be null in middleware mode.
*/
httpServer: http.Server | null
/**
* 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
*/
watcher: FSWatcher
/**
* WebSocket server with `send(payload)` method.
*/
ws: WebSocketServer
/**
* Rollup plugin container that can run plugin hooks on a given file.
*/
pluginContainer: PluginContainer
/**
* Module graph that tracks the import relationships, url to file mapping
* and hmr state.
*/
moduleGraph: ModuleGraph
/**
* 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.
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Programmatically resolve, load and transform a URL and get the result
* without going through the http request pipeline.
*/
transformRequest(
url: string,
options?: TransformOptions,
): Promise<TransformResult | null>
/**
* Apply Vite built-in HTML transforms and any plugin HTML transforms.
*/
transformIndexHtml(
url: string,
html: string,
originalUrl?: string,
): Promise<string>
/**
* Load a given URL as an instantiated module for SSR.
*/
ssrLoadModule(
url: string,
options?: { fixStacktrace?: boolean },
): Promise<Record<string, any>>
/**
* Fix ssr error stacktrace.
*/
ssrFixStacktrace(e: Error): 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.
*/
reloadModule(module: ModuleNode): Promise<void>
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
/**
* Restart the server.
*
* @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
*/
restart(forceOptimize?: boolean): Promise<void>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* Bind CLI shortcuts
*/
bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): 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
*/
waitForRequestsIdle: (ignoredId?: string) => Promise<void>
}INFO
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. 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.holdUntilCrawlEnd: false by default to avoid the performance hit in large applications during cold start.
build
Type Signature:
async function build(
inlineConfig?: InlineConfig,
): Promise<RolldownOutput | RolldownOutput[] | RolldownWatcher>Example Usage:
import pathconst path: path.PlatformPath from 'node:path'
import { buildfunction build(inlineConfig?: InlineConfig): Promise<RolldownOutput | RolldownOutput[] | RolldownWatcher>Bundles a single environment for production.
Returns a Promise containing the build result.
} from 'vite'
await buildfunction build(inlineConfig?: InlineConfig): Promise<RolldownOutput | RolldownOutput[] | RolldownWatcher>Bundles a single environment for production.
Returns a Promise containing the build result.
({
rootUserConfig.root?: string | undefinedProject root directory. Can be an absolute path, or a path relative from
the location of the config file itself.
: pathconst path: path.PlatformPath.resolvepath.PlatformPath.resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, './project'),
baseUserConfig.base?: string | undefinedBase public path when served in development or production.
: '/foo/',
buildbuild?: BuildEnvironmentOptions | undefinedBuild specific options
: {
rolldownOptionsBuildEnvironmentOptions.rolldownOptions?: RolldownOptions | undefinedWill be merged with internal rolldown options.
https://rolldown.rs/reference/Interface.RolldownOptions
: {
// ...
},
},
})preview
Type Signature:
async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>Example Usage:
import { previewfunction preview(inlineConfig?: InlineConfig): Promise<PreviewServer>Starts the Vite server in preview mode, to simulate a production deployment
} from 'vite'
const previewServerconst previewServer: PreviewServer = await previewfunction preview(inlineConfig?: InlineConfig): Promise<PreviewServer>Starts the Vite server in preview mode, to simulate a production deployment
({
// any valid user config options, plus `mode` and `configFile`
previewUserConfig.preview?: PreviewOptions | undefinedPreview specific options, e.g. host, port, https...
: {
portCommonServerOptions.port?: number | undefinedSpecify 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.
: 8080,
openCommonServerOptions.open?: string | boolean | undefinedOpen browser window on startup
: true,
},
})
previewServerconst previewServer: PreviewServer.printUrlsPreviewServer.printUrls(): voidPrint server urls
()
previewServerconst previewServer: PreviewServer.bindCLIShortcutsPreviewServer.bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): voidBind CLI shortcuts
({ printprint?: boolean | undefinedPrint a one-line shortcuts "help" hint to the terminal
: true })PreviewServer
interface PreviewServer {
/**
* The resolved vite config object
*/
config: ResolvedConfig
/**
* A connect app instance.
* - Can be used to attach custom middlewares to the preview 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
*/
middlewares: Connect.Server
/**
* native Node http server instance
*/
httpServer: http.Server
/**
* The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
* if the server is not listening on any port.
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Print server urls
*/
printUrls(): void
/**
* Bind CLI shortcuts
*/
bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void
}resolveConfig
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
Type Signature:
function mergeConfig(
defaults: Record<string, any>,
overrides: Record<string, any>,
isRoot = true,
): Record<string, any>Deeply merge two Vite configs. isRoot represents the level within the Vite config which is being merged. For example, set false if you're merging two build options.
Note that 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.
NOTE
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 defineConfigfunction defineConfig(config: UserConfigFnObject): UserConfigFnObject (+5 overloads)Type helper to make it easier to use vite.config.ts
accepts a direct
UserConfig
object, or a function that returns it.
The function receives a
ConfigEnv
object.
((configEnvconfigEnv: ConfigEnv) =>
mergeConfigmergeConfig<UserConfig, UserConfig>(defaults: UserConfig, overrides: UserConfig, isRoot?: boolean): Record<string, any>(configAsCallbackconst configAsCallback: (env: ConfigEnv) => UserConfig(configEnvconfigEnv: ConfigEnv), configAsObjectconst configAsObject: UserConfig),
)searchForWorkspaceRoot
Type Signature:
function searchForWorkspaceRoot(
current: string,
root = searchForPackageRoot(current),
): stringRelated: server.fs.allow
Search for the root of the potential workspace if it meets the following conditions, otherwise it would fallback to root:
- contains
workspacesfield inpackage.json - contains one of the following file
lerna.jsonpnpm-workspace.yaml
loadEnv
Type Signature:
function loadEnv(
mode: string,
envDir: string,
prefixes: string | string[] = 'VITE_',
): Record<string, string>Related: .env Files
Load .env files within the envDir and merge them with the matching variables already present in process.env. By default, only env variables prefixed with VITE_ are loaded, unless prefixes is changed.
normalizePath
Type Signature:
function normalizePath(id: string): stringRelated: Path Normalization
Normalizes a path to interoperate between Vite plugins.
transformWithOxc
Type Signature:
async function transformWithOxc(
code: string,
filename: string,
options?: OxcTransformOptions,
inMap?: object,
): Promise<Omit<OxcTransformResult, 'errors'> & { warnings: string[] }>Transform JavaScript or TypeScript with Oxc Transformer. Useful for plugins that prefer matching Vite's internal Oxc Transformer transform.
transformWithEsbuild
Type Signature:
async function transformWithEsbuild(
code: string,
filename: string,
options?: EsbuildTransformOptions,
inMap?: object,
): Promise<ESBuildTransformResult>Deprecated: Use transformWithOxc instead.
Transform JavaScript or TypeScript with esbuild. Useful for plugins that prefer matching Vite's internal esbuild transform.
loadConfigFromFile
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>Load a Vite config file manually with Rolldown.
preprocessCSS
- Experimental: Give Feedback
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>
}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. Similar to the built-in CSS pre-processing support, the corresponding pre-processor must be installed if used.
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.
Note that pre-processing will not resolve URLs in url() or image-set().
version
Type: string
The current version of Vite as a string (e.g. "8.0.0").
rolldownVersion
Type: string
The version of Rolldown used by Vite as a string (e.g. "1.0.0"). A re-export of VERSION from rolldown.
esbuildVersion
Type: string
Only kept for backward compatibility.
rollupVersion
Type: string
Only kept for backward compatibility.
