vite
- Version 6.0.7
- Published
- 2.82 MB
- 3 dependencies
- MIT license
Install
npm i vite
yarn add vite
pnpm add vite
Overview
Native-ESM powered web dev build tool
Index
Variables
Functions
- build()
- buildErrorMessage()
- createBuilder()
- createFilter()
- createIdResolver()
- createLogger()
- createRunnableDevEnvironment()
- createServer()
- createServerHotChannel()
- createServerModuleRunner()
- defineConfig()
- fetchModule()
- formatPostcssSourceMap()
- isCSSRequest()
- isFileLoadingAllowed()
- isFileServingAllowed()
- isRunnableDevEnvironment()
- loadConfigFromFile()
- loadEnv()
- mergeAlias()
- mergeConfig()
- moduleRunnerTransform()
- normalizePath()
- optimizeDeps()
- perEnvironmentPlugin()
- perEnvironmentState()
- preprocessCSS()
- preview()
- resolveConfig()
- resolveEnvPrefix()
- searchForWorkspaceRoot()
- send()
- sortUserPlugins()
- splitVendorChunk()
- splitVendorChunkPlugin()
- transformWithEsbuild()
Classes
ModuleGraph
- createFileOnlyEntry()
- ensureEntryFromUrl()
- etagToModuleMap
- fileToModulesMap
- getBackwardCompatibleBrowserModuleNode()
- getBackwardCompatibleModuleNode()
- getBackwardCompatibleModuleNodeDual()
- getBackwardCompatibleServerModuleNode()
- getModuleByEtag()
- getModuleById()
- getModuleByUrl()
- getModulesByFile()
- idToModuleMap
- invalidateAll()
- invalidateModule()
- onFileChange()
- onFileDelete()
- resolveUrl()
- updateModuleTransformResult()
- urlToModuleMap
Interfaces
BuildEnvironmentOptions
- assetsDir
- assetsInlineLimit
- chunkSizeWarningLimit
- commonjsOptions
- copyPublicDir
- createEnvironment
- cssCodeSplit
- cssMinify
- cssTarget
- dynamicImportVarsOptions
- emitAssets
- emptyOutDir
- lib
- manifest
- minify
- modulePreload
- outDir
- polyfillModulePreload
- reportCompressedSize
- rollupOptions
- sourcemap
- ssr
- ssrEmitAssets
- ssrManifest
- target
- terserOptions
- watch
- write
ViteDevServer
- bindCLIShortcuts()
- close()
- config
- environments
- hot
- httpServer
- listen()
- middlewares
- moduleGraph
- openBrowser()
- pluginContainer
- printUrls()
- reloadModule()
- resolvedUrls
- restart()
- ssrFixStacktrace()
- ssrLoadModule()
- ssrRewriteStacktrace()
- ssrTransform()
- transformIndexHtml()
- transformRequest()
- waitForRequestsIdle
- warmupRequest()
- watcher
- ws
Type Aliases
- AliasOptions
- AnymatchFn
- AnymatchPattern
- AppType
- BindCLIShortcutsOptions
- BuildOptions
- CLIShortcut
- CorsOrigin
- DepOptimizationOptions
- Environment
- ESBuildTransformResult
- ExportsData
- FilterPattern
- GeneralImportGlobOptions
- HMRBroadcaster
- HMRBroadcasterClient
- HMRChannel
- HMRPayload
- HookHandler
- HotChannelListener
- HotPayload
- HttpServer
- IndexHtmlTransform
- IndexHtmlTransformHook
- IndexHtmlTransformResult
- InferCustomEventPayload
- LessPreprocessorOptions
- LibraryFormats
- LightningCSSOptions
- LogLevel
- LogType
- Manifest
- MapToFunction
- Matcher
- PluginOption
- PreviewServerHook
- RenderBuiltAssetUrl
- ResolvedConfig
- ResolvedCSSOptions
- ResolvedDevEnvironmentOptions
- ResolvedUrl
- ResolveFn
- ResolveModulePreloadDependenciesFn
- ResolverFunction
- SassPreprocessorOptions
- ServerHMRChannel
- ServerHook
- ServerHotChannel
- SkipInformation
- SsrDepOptimizationConfig
- SSRTarget
- StylusPreprocessorOptions
- UserConfigExport
- UserConfigFn
- UserConfigFnObject
- UserConfigFnPromise
- WebSocketCustomListener
Namespaces
Variables
variable defaultClientConditions
const defaultClientConditions: readonly string[];
variable defaultClientMainFields
const defaultClientMainFields: readonly string[];
variable defaultServerConditions
const defaultServerConditions: readonly string[];
variable defaultServerMainFields
const defaultServerMainFields: readonly string[];
variable isWebSocketServer
const isWebSocketServer: Symbol;
variable rollupVersion
const rollupVersion: string;
variable version
const version: string;
variable WebSocketAlias
const WebSocketAlias: typeof WebSocket;
Functions
function build
build: ( inlineConfig?: InlineConfig) => Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
Bundles a single environment for production. Returns a Promise containing the build result.
function buildErrorMessage
buildErrorMessage: ( err: RollupError, args?: string[], includeStack?: boolean) => string;
function createBuilder
createBuilder: ( inlineConfig?: InlineConfig, useLegacyBuilder?: null | boolean) => Promise<ViteBuilder>;
Creates a ViteBuilder to orchestrate building multiple environments.
Modifiers
@experimental
function createFilter
createFilter: ( include?: FilterPattern, exclude?: FilterPattern, options?: { resolve?: string | false | null }) => (id: string | unknown) => boolean;
function createIdResolver
createIdResolver: ( config: ResolvedConfig, options?: Partial<InternalResolveOptions>) => ResolveIdFn;
Create an internal resolver to be used in special scenarios, e.g. optimizer and handling css
function createLogger
createLogger: (level?: LogLevel, options?: LoggerOptions) => Logger;
function createRunnableDevEnvironment
createRunnableDevEnvironment: ( name: string, config: ResolvedConfig, context?: RunnableDevEnvironmentContext) => RunnableDevEnvironment;
function createServer
createServer: (inlineConfig?: InlineConfig) => Promise<ViteDevServer>;
function createServerHotChannel
createServerHotChannel: () => ServerHotChannel;
function createServerModuleRunner
createServerModuleRunner: ( environment: DevEnvironment, options?: ServerModuleRunnerOptions) => ModuleRunner;
Create an instance of the Vite SSR runtime that support HMR.
Modifiers
@experimental
function defineConfig
defineConfig: { (config: UserConfig): UserConfig; (config: Promise<UserConfig>): Promise<UserConfig>; (config: UserConfigFnObject): UserConfigFnObject; (config: UserConfigFnPromise): UserConfigFnPromise; (config: UserConfigFn): UserConfigFn; (config: UserConfigExport): UserConfigExport;};
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.
function fetchModule
fetchModule: ( environment: DevEnvironment, url: string, importer?: string, options?: FetchModuleOptions) => Promise<FetchResult>;
Fetch module information for Vite runner.
Modifiers
@experimental
function formatPostcssSourceMap
formatPostcssSourceMap: ( rawMap: ExistingRawSourceMap, file: string) => Promise<ExistingRawSourceMap>;
function isCSSRequest
isCSSRequest: (request: string) => boolean;
function isFileLoadingAllowed
isFileLoadingAllowed: (config: ResolvedConfig, filePath: string) => boolean;
function isFileServingAllowed
isFileServingAllowed: { (config: ResolvedConfig, url: string): boolean; (url: string, server: ViteDevServer): boolean;};
Check if the url is allowed to be served, via the
server.fs
config.Deprecated
Use the
isFileServingAllowed(config, url)
signature instead.
function isRunnableDevEnvironment
isRunnableDevEnvironment: ( environment: Environment) => environment is RunnableDevEnvironment;
function loadConfigFromFile
loadConfigFromFile: ( configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel, customLogger?: Logger) => Promise<{ path: string; config: UserConfig; dependencies: string[] } | null>;
function loadEnv
loadEnv: ( mode: string, envDir: string, prefixes?: string | string[]) => Record<string, string>;
function mergeAlias
mergeAlias: (a?: AliasOptions, b?: AliasOptions) => AliasOptions | undefined;
function mergeConfig
mergeConfig: <D extends Record<string, any>, O extends Record<string, any>>( defaults: D extends Function ? never : D, overrides: O extends Function ? never : O, isRoot?: boolean) => Record<string, any>;
function moduleRunnerTransform
moduleRunnerTransform: ( code: string, inMap: SourceMap | { mappings: '' } | null, url: string, originalCode: string, options?: ModuleRunnerTransformOptions) => Promise<TransformResult | null>;
function normalizePath
normalizePath: (id: string) => string;
function optimizeDeps
optimizeDeps: ( config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean) => Promise<DepOptimizationMetadata>;
Scan and optimize dependencies within a project. Used by Vite CLI when running
vite optimize
.
function perEnvironmentPlugin
perEnvironmentPlugin: ( name: string, applyToEnvironment: ( environment: PartialEnvironment ) => boolean | Promise<boolean> | PluginOption) => Plugin;
Modifiers
@experimental
function perEnvironmentState
perEnvironmentState: <State>( initial: (environment: Environment) => State) => (context: PluginContext) => State;
Creates a function that hides the complexities of a WeakMap with an initial value to implement object metadata. Used by plugins to implement cross hooks per environment metadata
Modifiers
@experimental
function preprocessCSS
preprocessCSS: ( code: string, filename: string, config: ResolvedConfig) => Promise<PreprocessCSSResult>;
Modifiers
@experimental
function preview
preview: (inlineConfig?: InlineConfig) => Promise<PreviewServer>;
Starts the Vite server in preview mode, to simulate a production deployment
function resolveConfig
resolveConfig: ( inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string, defaultNodeEnv?: string, isPreview?: boolean) => Promise<ResolvedConfig>;
function resolveEnvPrefix
resolveEnvPrefix: ({ envPrefix }: UserConfig) => string[];
function searchForWorkspaceRoot
searchForWorkspaceRoot: (current: string, root?: string) => string;
Search up for the nearest workspace root
function send
send: ( req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions) => void;
function sortUserPlugins
sortUserPlugins: ( plugins: (Plugin | Plugin[])[] | undefined) => [Plugin[], Plugin[], Plugin[]];
function splitVendorChunk
splitVendorChunk: (options?: { cache?: SplitVendorChunkCache;}) => GetManualChunk;
Deprecated
use build.rollupOptions.output.manualChunks or framework specific configuration
function splitVendorChunkPlugin
splitVendorChunkPlugin: () => Plugin;
Deprecated
use build.rollupOptions.output.manualChunks or framework specific configuration
function transformWithEsbuild
transformWithEsbuild: ( code: string, filename: string, options?: esbuild_TransformOptions, inMap?: object, config?: ResolvedConfig, watcher?: FSWatcher) => Promise<ESBuildTransformResult>;
Classes
class BuildEnvironment
class BuildEnvironment extends BaseEnvironment {}
constructor
constructor( name: string, config: Readonly< Omit< UserConfig, | 'plugins' | 'css' | 'json' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build' | 'dev' | 'environments' | 'server' | 'preview' > & { configFile: string; configFileDependencies: string[]; inlineConfig: InlineConfig; root: string; base: string; publicDir: string; cacheDir: string; command: 'build' | 'serve'; mode: string; isWorker: boolean; isProduction: boolean; envDir: string; env: Record<string, any>; resolve: Required<ResolveOptions> & { alias: Alias[] }; plugins: readonly Plugin<any>[]; css: ResolvedCSSOptions; json: Required<JsonOptions>; esbuild: false | ESBuildOptions; server: ResolvedServerOptions; dev: ResolvedDevEnvironmentOptions; builder: Required<BuilderOptions>; build: ResolvedBuildOptions; preview: ResolvedPreviewOptions; ssr: ResolvedSSROptions; assetsInclude: (file: string) => boolean; logger: Logger; createResolver: ( options?: Partial<InternalResolveOptions> ) => ResolveFn; optimizeDeps: DepOptimizationOptions; worker: ResolvedWorkerOptions; appType: AppType; experimental: ExperimentalOptions; environments: Record<string, ResolvedEnvironmentOptions>; } & PluginHookUtils >, setup?: { options?: EnvironmentOptions });
property mode
mode: string;
method init
init: () => Promise<void>;
class DevEnvironment
class DevEnvironment extends BaseEnvironment {}
constructor
constructor( name: string, config: Readonly< Omit< UserConfig, | 'plugins' | 'css' | 'json' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build' | 'dev' | 'environments' | 'server' | 'preview' > & { configFile: string; configFileDependencies: string[]; inlineConfig: InlineConfig; root: string; base: string; publicDir: string; cacheDir: string; command: 'build' | 'serve'; mode: string; isWorker: boolean; isProduction: boolean; envDir: string; env: Record<string, any>; resolve: Required<ResolveOptions> & { alias: Alias[] }; plugins: readonly Plugin<any>[]; css: ResolvedCSSOptions; json: Required<JsonOptions>; esbuild: false | ESBuildOptions; server: ResolvedServerOptions; dev: ResolvedDevEnvironmentOptions; builder: Required<BuilderOptions>; build: ResolvedBuildOptions; preview: ResolvedPreviewOptions; ssr: ResolvedSSROptions; assetsInclude: (file: string) => boolean; logger: Logger; createResolver: ( options?: Partial<InternalResolveOptions> ) => ResolveFn; optimizeDeps: DepOptimizationOptions; worker: ResolvedWorkerOptions; appType: AppType; experimental: ExperimentalOptions; environments: Record<string, ResolvedEnvironmentOptions>; } & PluginHookUtils >, context: DevEnvironmentContext);
property depsOptimizer
depsOptimizer?: DepsOptimizer;
property hot
hot: NormalizedHotChannel<any>;
Hot channel for this environment. If not provided or disabled, it will be a noop channel that does nothing.
Example 1
environment.hot.send({ type: 'full-reload' })
property mode
mode: string;
property moduleGraph
moduleGraph: EnvironmentModuleGraph;
property pluginContainer
readonly pluginContainer: EnvironmentPluginContainer;
method close
close: () => Promise<void>;
method fetchModule
fetchModule: ( id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
method init
init: (options?: { watcher?: FSWatcher; previousInstance?: DevEnvironment;}) => Promise<void>;
method listen
listen: (server: ViteDevServer) => Promise<void>;
When the dev server is restarted, the methods are called in the following order: - new instance
init
- previous instanceclose
- new instancelisten
method reloadModule
reloadModule: (module: EnvironmentModuleNode) => Promise<void>;
method transformRequest
transformRequest: (url: string) => Promise<TransformResult | null>;
method waitForRequestsIdle
waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
Calling
await environment.waitForRequestsIdle(id)
will wait until all static imports are processed after the first transformRequest call. 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.Modifiers
@experimental
method warmupRequest
warmupRequest: (url: string) => Promise<void>;
class EnvironmentModuleGraph
class EnvironmentModuleGraph {}
constructor
constructor( environment: string, resolveId: (url: string) => Promise<PartialResolvedId | null>);
property environment
environment: string;
property etagToModuleMap
etagToModuleMap: Map<string, EnvironmentModuleNode>;
property fileToModulesMap
fileToModulesMap: Map<string, Set<EnvironmentModuleNode>>;
property idToModuleMap
idToModuleMap: Map<string, EnvironmentModuleNode>;
property urlToModuleMap
urlToModuleMap: Map<string, EnvironmentModuleNode>;
method createFileOnlyEntry
createFileOnlyEntry: (file: string) => EnvironmentModuleNode;
method ensureEntryFromUrl
ensureEntryFromUrl: ( rawUrl: string, setIsSelfAccepting?: boolean) => Promise<EnvironmentModuleNode>;
method getModuleByEtag
getModuleByEtag: (etag: string) => EnvironmentModuleNode | undefined;
method getModuleById
getModuleById: (id: string) => EnvironmentModuleNode | undefined;
method getModuleByUrl
getModuleByUrl: (rawUrl: string) => Promise<EnvironmentModuleNode | undefined>;
method getModulesByFile
getModulesByFile: (file: string) => Set<EnvironmentModuleNode> | undefined;
method invalidateAll
invalidateAll: () => void;
method invalidateModule
invalidateModule: ( mod: EnvironmentModuleNode, seen?: Set<EnvironmentModuleNode>, timestamp?: number, isHmr?: boolean) => void;
method onFileChange
onFileChange: (file: string) => void;
method onFileDelete
onFileDelete: (file: string) => void;
method resolveUrl
resolveUrl: (url: string) => Promise<ResolvedUrl>;
method updateModuleInfo
updateModuleInfo: ( mod: EnvironmentModuleNode, importedModules: Set<string | EnvironmentModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | EnvironmentModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean) => Promise<Set<EnvironmentModuleNode> | undefined>;
Update the module graph based on a module's updated imports information If there are dependencies that no longer have any importers, they are returned as a Set.
Parameter staticImportedUrls
Subset of
importedModules
where they're statically imported in code. This is only used for soft invalidations soundefined
is fine but may cause more runtime processing.
method updateModuleTransformResult
updateModuleTransformResult: ( mod: EnvironmentModuleNode, result: TransformResult | null) => void;
class EnvironmentModuleNode
class EnvironmentModuleNode {}
constructor
constructor(url: string, environment: string, setIsSelfAccepting?: boolean);
Parameter setIsSelfAccepting
set
false
to setisSelfAccepting
later. e.g. #7870
property acceptedHmrDeps
acceptedHmrDeps: Set<EnvironmentModuleNode>;
property acceptedHmrExports
acceptedHmrExports: Set<string>;
property environment
environment: string;
property file
file: string;
property id
id: string;
Resolved file system path + query
property importedBindings
importedBindings: Map<string, Set<string>>;
property importedModules
importedModules: Set<EnvironmentModuleNode>;
property importers
importers: Set<EnvironmentModuleNode>;
property info
info?: ModuleInfo;
property isSelfAccepting
isSelfAccepting?: boolean;
property lastHMRTimestamp
lastHMRTimestamp: number;
property lastInvalidationTimestamp
lastInvalidationTimestamp: number;
property meta
meta?: Record<string, any>;
property ssrError
ssrError: Error;
property ssrModule
ssrModule: Record<string, any>;
property transformResult
transformResult: TransformResult;
property type
type: 'css' | 'js';
property url
url: string;
Public served url path, starts with /
class FSWatcher
class FSWatcher extends EventEmitter implements fs.FSWatcher {}
constructor
constructor(options?: WatchOptions);
Constructs a new FSWatcher instance with optional WatchOptions parameter.
property options
options: WatchOptions;
method add
add: (paths: string | ReadonlyArray<string>) => this;
Add files, directories, or glob patterns for tracking. Takes an array of strings or just one string.
method close
close: () => Promise<void>;
Removes all listeners from watched files.
method getWatched
getWatched: () => { [directory: string]: string[] };
Returns an object representing all the paths on the file system being watched by this
FSWatcher
instance. The object's keys are all the directories (using absolute paths unless thecwd
option was used), and the values are arrays of the names of the items contained in each directory.
method on
on: { ( event: 'add' | 'addDir' | 'change', listener: (path: string, stats?: fs.Stats) => void ): this; ( event: 'all', listener: ( eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', path: string, stats?: fs.Stats ) => void ): this; (event: 'error', listener: (error: Error) => void): this; ( event: 'raw', listener: (eventName: string, path: string, details: any) => void ): this; (event: 'ready', listener: () => void): this; (event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this; (event: string, listener: (...args: any[]) => void): this;};
Error occurred
Exposes the native Node
fs.FSWatcher events
Fires when the initial scan is complete
method ref
ref: () => this;
When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active. Calling watcher.ref() multiple times will have no effect.
method unref
unref: () => this;
When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked. Calling watcher.unref() multiple times will have no effect.
method unwatch
unwatch: (paths: string | ReadonlyArray<string>) => this;
Stop watching files, directories, or glob patterns. Takes an array of strings or just one string.
class ModuleGraph
class ModuleGraph {}
constructor
constructor(moduleGraphs: { client: () => EnvironmentModuleGraph; ssr: () => EnvironmentModuleGraph;});
property etagToModuleMap
etagToModuleMap: Map<string, ModuleNode>;
property fileToModulesMap
fileToModulesMap: Map<string, Set<ModuleNode>>;
property idToModuleMap
idToModuleMap: Map<string, ModuleNode>;
property urlToModuleMap
urlToModuleMap: Map<string, ModuleNode>;
method createFileOnlyEntry
createFileOnlyEntry: (file: string) => ModuleNode;
method ensureEntryFromUrl
ensureEntryFromUrl: ( rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean) => Promise<ModuleNode>;
method getBackwardCompatibleBrowserModuleNode
getBackwardCompatibleBrowserModuleNode: ( clientModule: EnvironmentModuleNode) => ModuleNode;
method getBackwardCompatibleModuleNode
getBackwardCompatibleModuleNode: (mod: EnvironmentModuleNode) => ModuleNode;
method getBackwardCompatibleModuleNodeDual
getBackwardCompatibleModuleNodeDual: ( clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode) => ModuleNode;
method getBackwardCompatibleServerModuleNode
getBackwardCompatibleServerModuleNode: ( ssrModule: EnvironmentModuleNode) => ModuleNode;
method getModuleByEtag
getModuleByEtag: (etag: string) => ModuleNode | undefined;
method getModuleById
getModuleById: (id: string) => ModuleNode | undefined;
method getModuleByUrl
getModuleByUrl: (url: string, _ssr?: boolean) => Promise<ModuleNode | undefined>;
method getModulesByFile
getModulesByFile: (file: string) => Set<ModuleNode> | undefined;
method invalidateAll
invalidateAll: () => void;
method invalidateModule
invalidateModule: ( mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean) => void;
method onFileChange
onFileChange: (file: string) => void;
method onFileDelete
onFileDelete: (file: string) => void;
method resolveUrl
resolveUrl: (url: string, ssr?: boolean) => Promise<ResolvedUrl>;
method updateModuleTransformResult
updateModuleTransformResult: ( mod: ModuleNode, result: TransformResult | null, ssr?: boolean) => void;
class ModuleNode
class ModuleNode {}
constructor
constructor( moduleGraph: ModuleGraph, clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode);
property acceptedHmrDeps
readonly acceptedHmrDeps: Set<ModuleNode>;
property acceptedHmrExports
readonly acceptedHmrExports: Set<string>;
property clientImportedModules
readonly clientImportedModules: Set<ModuleNode>;
property file
file: string;
property id
id: string;
property importedBindings
readonly importedBindings: Map<string, Set<string>>;
property importedModules
readonly importedModules: Set<ModuleNode>;
property importers
readonly importers: Set<ModuleNode>;
property info
readonly info: any;
property invalidationState
readonly invalidationState: TransformResult | 'HARD_INVALIDATED';
property isSelfAccepting
readonly isSelfAccepting: boolean;
property lastHMRTimestamp
lastHMRTimestamp: number;
property lastInvalidationTimestamp
readonly lastInvalidationTimestamp: number;
property meta
readonly meta: Record<string, any>;
property ssrError
readonly ssrError: Error;
property ssrImportedModules
readonly ssrImportedModules: Set<ModuleNode>;
property ssrInvalidationState
readonly ssrInvalidationState: TransformResult | 'HARD_INVALIDATED';
property ssrModule
readonly ssrModule: Record<string, any>;
property ssrTransformResult
ssrTransformResult: TransformResult;
property transformResult
transformResult: TransformResult;
property type
readonly type: 'css' | 'js';
property url
url: string;
class PluginContainer
class PluginContainer {}
constructor
constructor(environments: Record<string, Environment>);
property options
readonly options: InputOptions;
method buildStart
buildStart: (_options?: InputOptions) => Promise<void>;
method close
close: () => Promise<void>;
method getModuleInfo
getModuleInfo: (id: string) => ModuleInfo | null;
method load
load: (id: string, options?: { ssr?: boolean }) => Promise<LoadResult | null>;
method resolveId
resolveId: ( rawId: string, importer?: string, options?: { attributes?: Record<string, string>; custom?: CustomPluginOptions; skip?: Set<Plugin>; skipCalls?: readonly SkipInformation[]; ssr?: boolean; isEntry?: boolean; }) => Promise<PartialResolvedId | null>;
method transform
transform: ( code: string, id: string, options?: { ssr?: boolean; environment?: Environment; inMap?: SourceDescription['map']; }) => Promise<{ code: string; map: SourceMap | { mappings: '' } | null }>;
method watchChange
watchChange: ( id: string, change: { event: 'create' | 'update' | 'delete' }) => Promise<void>;
class RunnableDevEnvironment
class RunnableDevEnvironment extends DevEnvironment {}
constructor
constructor( name: string, config: Readonly< Omit< UserConfig, | 'plugins' | 'css' | 'json' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build' | 'dev' | 'environments' | 'server' | 'preview' > & { configFile: string; configFileDependencies: string[]; inlineConfig: InlineConfig; root: string; base: string; publicDir: string; cacheDir: string; command: 'build' | 'serve'; mode: string; isWorker: boolean; isProduction: boolean; envDir: string; env: Record<string, any>; resolve: Required<ResolveOptions> & { alias: Alias[] }; plugins: readonly Plugin<any>[]; css: ResolvedCSSOptions; json: Required<JsonOptions>; esbuild: false | ESBuildOptions; server: ResolvedServerOptions; dev: ResolvedDevEnvironmentOptions; builder: Required<BuilderOptions>; build: ResolvedBuildOptions; preview: ResolvedPreviewOptions; ssr: ResolvedSSROptions; assetsInclude: (file: string) => boolean; logger: Logger; createResolver: ( options?: Partial<InternalResolveOptions> ) => ResolveFn; optimizeDeps: DepOptimizationOptions; worker: ResolvedWorkerOptions; appType: AppType; experimental: ExperimentalOptions; environments: Record<string, ResolvedEnvironmentOptions>; } & PluginHookUtils >, context: RunnableDevEnvironmentContext);
property runner
readonly runner: ModuleRunner;
method close
close: () => Promise<void>;
class SplitVendorChunkCache
class SplitVendorChunkCache {}
Deprecated
use build.rollupOptions.output.manualChunks or framework specific configuration
class WebSocket
class WebSocket extends EventEmitter {}
constructor
constructor(address: null);
constructor
constructor(address: any, options?: any);
constructor
constructor(address: any, protocols?: string | string[], options?: any);
property binaryType
binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments';
property bufferedAmount
readonly bufferedAmount: number;
property CLOSED
static readonly CLOSED: number;
The connection is closed.
property CLOSED
readonly CLOSED: number;
The connection is closed.
property CLOSING
static readonly CLOSING: number;
The connection is in the process of closing.
property CLOSING
readonly CLOSING: number;
The connection is in the process of closing.
property CONNECTING
static readonly CONNECTING: number;
The connection is not yet open.
property CONNECTING
readonly CONNECTING: number;
The connection is not yet open.
property extensions
readonly extensions: string;
property isPaused
readonly isPaused: boolean;
Indicates whether the websocket is paused
property onclose
onclose: (event: WebSocket.CloseEvent) => void;
property onerror
onerror: (event: WebSocket.ErrorEvent) => void;
property onmessage
onmessage: (event: WebSocket.MessageEvent) => void;
property onopen
onopen: (event: WebSocket.Event) => void;
property OPEN
static readonly OPEN: number;
The connection is open and ready to communicate.
property OPEN
readonly OPEN: number;
The connection is open and ready to communicate.
property protocol
readonly protocol: string;
property readyState
readonly readyState: 0 | 3 | 1 | 2;
The current state of the connection
property url
readonly url: string;
method addEventListener
addEventListener: { ( method: 'message', cb: (event: WebSocket.MessageEvent) => void, options?: WebSocket.EventListenerOptions ): void; ( method: 'close', cb: (event: WebSocket.CloseEvent) => void, options?: WebSocket.EventListenerOptions ): void; ( method: 'error', cb: (event: WebSocket.ErrorEvent) => void, options?: WebSocket.EventListenerOptions ): void; ( method: 'open', cb: (event: WebSocket.Event) => void, options?: WebSocket.EventListenerOptions ): void;};
method addListener
addListener: { (event: 'close', listener: (code: number, reason: Buffer) => void): this; (event: 'error', listener: (err: Error) => void): this; (event: 'upgrade', listener: (request: IncomingMessage) => void): this; (event: 'message', listener: (data: any, isBinary: boolean) => void): this; (event: 'open', listener: () => void): this; (event: 'ping' | 'pong', listener: (data: Buffer) => void): this; ( event: 'unexpected-response', listener: (request: ClientRequest, response: IncomingMessage) => void ): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
method close
close: (code?: number, data?: string | Buffer) => void;
method off
off: { ( event: 'close', listener: (this: WebSocket, code: number, reason: Buffer) => void ): this; (event: 'error', listener: (this: WebSocket, err: Error) => void): this; ( event: 'upgrade', listener: (this: WebSocket, request: IncomingMessage) => void ): this; ( event: 'message', listener: (this: WebSocket, data: any, isBinary: boolean) => void ): this; (event: 'open', listener: (this: WebSocket) => void): this; ( event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void ): this; ( event: 'unexpected-response', listener: ( this: WebSocket, request: ClientRequest, response: IncomingMessage ) => void ): this; ( event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void ): this;};
method on
on: { ( event: 'close', listener: (this: WebSocket, code: number, reason: Buffer) => void ): this; (event: 'error', listener: (this: WebSocket, err: Error) => void): this; ( event: 'upgrade', listener: (this: WebSocket, request: IncomingMessage) => void ): this; ( event: 'message', listener: (this: WebSocket, data: any, isBinary: boolean) => void ): this; (event: 'open', listener: (this: WebSocket) => void): this; ( event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void ): this; ( event: 'unexpected-response', listener: ( this: WebSocket, request: ClientRequest, response: IncomingMessage ) => void ): this; ( event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void ): this;};
method once
once: { ( event: 'close', listener: (this: WebSocket, code: number, reason: Buffer) => void ): this; (event: 'error', listener: (this: WebSocket, err: Error) => void): this; ( event: 'upgrade', listener: (this: WebSocket, request: IncomingMessage) => void ): this; ( event: 'message', listener: (this: WebSocket, data: any, isBinary: boolean) => void ): this; (event: 'open', listener: (this: WebSocket) => void): this; ( event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void ): this; ( event: 'unexpected-response', listener: ( this: WebSocket, request: ClientRequest, response: IncomingMessage ) => void ): this; ( event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void ): this;};
method pause
pause: () => void;
Pause the websocket causing it to stop emitting events. Some events can still be emitted after this is called, until all buffered data is consumed. This method is a noop if the ready state is
CONNECTING
orCLOSED
.
method ping
ping: (data?: any, mask?: boolean, cb?: (err: Error) => void) => void;
method pong
pong: (data?: any, mask?: boolean, cb?: (err: Error) => void) => void;
method removeEventListener
removeEventListener: { (method: 'message', cb: (event: WebSocket.MessageEvent) => void): void; (method: 'close', cb: (event: WebSocket.CloseEvent) => void): void; (method: 'error', cb: (event: WebSocket.ErrorEvent) => void): void; (method: 'open', cb: (event: WebSocket.Event) => void): void;};
method removeListener
removeListener: { (event: 'close', listener: (code: number, reason: Buffer) => void): this; (event: 'error', listener: (err: Error) => void): this; (event: 'upgrade', listener: (request: IncomingMessage) => void): this; (event: 'message', listener: (data: any, isBinary: boolean) => void): this; (event: 'open', listener: () => void): this; (event: 'ping' | 'pong', listener: (data: Buffer) => void): this; ( event: 'unexpected-response', listener: (request: ClientRequest, response: IncomingMessage) => void ): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
method resume
resume: () => void;
Make a paused socket resume emitting events. This method is a noop if the ready state is
CONNECTING
orCLOSED
.
method send
send: { (data: any, cb?: (err?: Error) => void): void; ( data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean; }, cb?: (err?: Error) => void ): void;};
method terminate
terminate: () => void;
Interfaces
interface Alias
interface Alias {}
property customResolver
customResolver?: ResolverFunction | ResolverObject | null;
Instructs the plugin to use an alternative resolving algorithm, rather than the Rollup's resolver. null
property find
find: string | RegExp;
property replacement
replacement: string;
interface BuildEnvironmentOptions
interface BuildEnvironmentOptions {}
property assetsDir
assetsDir?: string;
Directory relative from
outDir
where the built js/css/image assets will be placed. 'assets'
property assetsInlineLimit
assetsInlineLimit?: | number | ((filePath: string, content: Buffer) => boolean | undefined);
Static asset files smaller than this number (in bytes) will be inlined as base64 strings. If a callback is passed, a boolean can be returned to opt-in or opt-out of inlining. If nothing is returned the default logic applies.
Default limit is
4096
(4 KiB). Set to0
to disable. 4096
property chunkSizeWarningLimit
chunkSizeWarningLimit?: number;
Adjust chunk size warning limit (in kB). 500
property commonjsOptions
commonjsOptions?: RollupCommonJSOptions;
Options to pass on to
@rollup/plugin-commonjs
property copyPublicDir
copyPublicDir?: boolean;
Copy the public directory to outDir on write. true
property createEnvironment
createEnvironment?: ( name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
create the Build Environment instance
property cssCodeSplit
cssCodeSplit?: boolean;
Whether to code-split CSS. When enabled, CSS in async chunks will be inlined as strings in the chunk and inserted via dynamically created style tags when the chunk is loaded. true
property cssMinify
cssMinify?: boolean | 'esbuild' | 'lightningcss';
Override CSS minification specifically instead of defaulting to
build.minify
, so you can configure minification for JS and CSS separately. 'esbuild'
property cssTarget
cssTarget?: esbuild_TransformOptions['target'] | false;
An optional separate target for CSS minification. As esbuild only supports configuring targets to mainstream browsers, users may need this option when they are targeting a niche browser that comes with most modern JavaScript features but has poor CSS support, e.g. Android WeChat WebView, which doesn't support the #RGBA syntax. target
property dynamicImportVarsOptions
dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
Options to pass on to
@rollup/plugin-dynamic-import-vars
property emitAssets
emitAssets?: boolean;
Emit assets during build. Frameworks can set environments.ssr.build.emitAssets By default, it is true for the client and false for other environments.
property emptyOutDir
emptyOutDir?: boolean | null;
Empty outDir on write. true when outDir is a sub directory of project root
property lib
lib?: LibraryOptions | false;
Build in library mode. The value should be the global name of the lib in UMD mode. This will produce esm + cjs + umd bundle formats with default configurations that are suitable for distributing libraries. false
property manifest
manifest?: boolean | string;
Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames to their hashed versions. Useful when you want to generate your own HTML instead of using the one generated by Vite.
Example:
{"main.js": {"file": "main.68fe3fad.js","css": "main.e6b63442.css","imports": [...],"dynamicImports": [...]}}false
property minify
minify?: boolean | 'terser' | 'esbuild';
Set to
false
to disable minification, or specify the minifier to use. Available options are 'terser' or 'esbuild'. 'esbuild'
property modulePreload
modulePreload?: boolean | ModulePreloadOptions;
Configure module preload Note: does not apply to library mode. true
property outDir
outDir?: string;
Directory relative from
root
where build output will be placed. If the directory exists, it will be removed before the build. 'dist'
property polyfillModulePreload
polyfillModulePreload?: boolean;
whether to inject module preload polyfill. Note: does not apply to library mode. true
Deprecated
use
modulePreload.polyfill
instead
property reportCompressedSize
reportCompressedSize?: boolean;
Set to false to disable reporting compressed chunk sizes. Can slightly improve build speed. true
property rollupOptions
rollupOptions?: RollupOptions;
Will be merged with internal rollup options. https://rollupjs.org/configuration-options/
property sourcemap
sourcemap?: boolean | 'inline' | 'hidden';
If
true
, a separate sourcemap file will be created. If 'inline', the sourcemap will be appended to the resulting output file as data URI. 'hidden' works liketrue
except that the corresponding sourcemap comments in the bundled files are suppressed. false
property ssr
ssr?: boolean | string;
Produce SSR oriented build. Note this requires specifying SSR entry via
rollupOptions.input
. false
property ssrEmitAssets
ssrEmitAssets?: boolean;
Emit assets during SSR. false
property ssrManifest
ssrManifest?: boolean | string;
Generate SSR manifest for determining style links and asset preload directives in production. false
property target
target?: 'modules' | esbuild_TransformOptions['target'] | false;
Compatibility transform target. The transform is performed with esbuild and the lowest supported target is es2015. Note this only handles syntax transformation and does not cover polyfills
Default: 'modules' - transpile targeting browsers that natively support dynamic es module imports and
import.meta
(Chrome 87+, Firefox 78+, Safari 14+, Edge 88+).Another special value is 'esnext' - which only performs minimal transpiling (for minification compat).
For custom targets, see https://esbuild.github.io/api/#target and https://esbuild.github.io/content-types/#javascript for more details. 'modules'
property terserOptions
terserOptions?: TerserOptions;
Options for terser https://terser.org/docs/api-reference#minify-options
In addition, you can also pass a
maxWorkers: number
option to specify the max number of workers to spawn. Defaults to the number of CPUs minus 1.
property watch
watch?: WatcherOptions | null;
Rollup watch options https://rollupjs.org/configuration-options/#watch null
property write
write?: boolean;
Whether to write bundle to disk true
interface BuilderOptions
interface BuilderOptions {}
property buildApp
buildApp?: (builder: ViteBuilder) => Promise<void>;
property sharedConfigBuild
sharedConfigBuild?: boolean;
Whether to share the config instance among environments to align with the behavior of dev server.
false
Modifiers
@experimental
property sharedPlugins
sharedPlugins?: boolean;
Whether to share the plugin instances among environments to align with the behavior of dev server.
false
Modifiers
@experimental
interface ChunkMetadata
interface ChunkMetadata {}
property importedAssets
importedAssets: Set<string>;
property importedCss
importedCss: Set<string>;
interface CommonServerOptions
interface CommonServerOptions {}
property cors
cors?: CorsOptions | boolean;
Configure CORS for the dev server. Uses https://github.com/expressjs/cors. Set to
true
to allow all methods from any origin, or configure separately using an object.
property headers
headers?: OutgoingHttpHeaders;
Specify server response headers.
property host
host?: string | boolean;
Specify which IP addresses the server should listen on. Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
property https
https?: HttpsServerOptions;
Enable TLS + HTTP/2. Note: this downgrades to TLS only when the proxy option is also used.
property open
open?: boolean | string;
Open browser window on startup
property port
port?: number;
Specify 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.
property proxy
proxy?: Record<string, string | ProxyOptions>;
Configure custom proxy rules for the dev server. Expects an object of
{ key: options }
pairs. Uses [http-proxy
](https://github.com/http-party/node-http-proxy). Full options [here](https://github.com/http-party/node-http-proxy#options).Example
vite.config.js
:module.exports = {proxy: {// string shorthand: /foo -> http://localhost:4567/foo'/foo': 'http://localhost:4567',// with options'/api': {target: 'http://jsonplaceholder.typicode.com',changeOrigin: true,rewrite: path => path.replace(/^\/api/, '')}}}
property strictPort
strictPort?: boolean;
If enabled, vite will exit if specified port is already in use
interface ConfigEnv
interface ConfigEnv {}
property command
command: 'build' | 'serve';
'serve': during dev (
vite
command) 'build': when building for production (vite build
command)
property isPreview
isPreview?: boolean;
property isSsrBuild
isSsrBuild?: boolean;
property mode
mode: string;
interface ConnectedPayload
interface ConnectedPayload {}
property type
type: 'connected';
interface CorsOptions
interface CorsOptions {}
https://github.com/expressjs/cors#configuration-options
property allowedHeaders
allowedHeaders?: string | string[];
property credentials
credentials?: boolean;
property exposedHeaders
exposedHeaders?: string | string[];
property maxAge
maxAge?: number;
property methods
methods?: string | string[];
property optionsSuccessStatus
optionsSuccessStatus?: number;
property origin
origin?: | CorsOrigin | (( origin: string | undefined, cb: (err: Error, origins: CorsOrigin) => void ) => void);
property preflightContinue
preflightContinue?: boolean;
interface CSSModulesOptions
interface CSSModulesOptions {}
property exportGlobals
exportGlobals?: boolean;
property generateScopedName
generateScopedName?: | string | ((name: string, filename: string, css: string) => string);
property getJSON
getJSON?: ( cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
property globalModulePaths
globalModulePaths?: RegExp[];
property hashPrefix
hashPrefix?: string;
property localsConvention
localsConvention?: | 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | (( originalClassName: string, generatedClassName: string, inputFile: string ) => string);
default: undefined
property scopeBehaviour
scopeBehaviour?: 'global' | 'local';
interface CSSOptions
interface CSSOptions {}
property devSourcemap
devSourcemap?: boolean;
Enables css sourcemaps during dev false
Modifiers
@experimental
property lightningcss
lightningcss?: LightningCSSOptions;
Modifiers
@experimental
property modules
modules?: CSSModulesOptions | false;
https://github.com/css-modules/postcss-modules
property postcss
postcss?: | string | (PostCSS.ProcessOptions & { plugins?: PostCSS.AcceptedPlugin[]; });
property preprocessorMaxWorkers
preprocessorMaxWorkers?: number | true;
If this option is set, preprocessors will run in workers when possible.
true
means the number of CPUs minus 1.0
Modifiers
@experimental
property preprocessorOptions
preprocessorOptions?: { scss?: SassPreprocessorOptions; sass?: SassPreprocessorOptions; less?: LessPreprocessorOptions; styl?: StylusPreprocessorOptions; stylus?: StylusPreprocessorOptions;};
Options for preprocessors.
In addition to options specific to each processors, Vite supports
additionalData
option. TheadditionalData
option can be used to inject extra code for each style content.
property transformer
transformer?: 'postcss' | 'lightningcss';
Using lightningcss is an experimental option to handle CSS modules, assets and imports via Lightning CSS. It requires to install it as a peer dependency. This is incompatible with the use of preprocessors.
'postcss'
Modifiers
@experimental
interface CustomEventMap
interface CustomEventMap {}
property 'vite:afterUpdate'
'vite:afterUpdate': UpdatePayload;
property 'vite:beforeFullReload'
'vite:beforeFullReload': FullReloadPayload;
property 'vite:beforePrune'
'vite:beforePrune': PrunePayload;
property 'vite:beforeUpdate'
'vite:beforeUpdate': UpdatePayload;
property 'vite:error'
'vite:error': ErrorPayload;
property 'vite:invalidate'
'vite:invalidate': InvalidatePayload;
property 'vite:ws:connect'
'vite:ws:connect': WebSocketConnectionPayload;
property 'vite:ws:disconnect'
'vite:ws:disconnect': WebSocketConnectionPayload;
interface CustomPayload
interface CustomPayload {}
interface DepOptimizationConfig
interface DepOptimizationConfig {}
property disabled
disabled?: boolean | 'build' | 'dev';
Deps optimization during build was removed in Vite 5.1. This option is now redundant and will be removed in a future version. Switch to using
optimizeDeps.noDiscovery
and an empty or undefinedoptimizeDeps.include
. true or 'dev' disables the optimizer, false or 'build' leaves it enabled. 'build'Modifiers
@experimental
Deprecated
property esbuildOptions
esbuildOptions?: Omit< esbuild_BuildOptions, | 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
Options to pass to esbuild during the dep scanning and optimization
Certain options are omitted since changing them would not be compatible with Vite's dep optimization.
-
external
is also omitted, use Vite'soptimizeDeps.exclude
option -plugins
are merged with Vite's dep pluginhttps://esbuild.github.io/api
property exclude
exclude?: string[];
Do not optimize these dependencies (must be resolvable import paths, cannot be globs).
property extensions
extensions?: string[];
List of file extensions that can be optimized. A corresponding esbuild plugin must exist to handle the specific extension.
By default, Vite can optimize
.mjs
,.js
,.ts
, and.mts
files. This option allows specifying additional extensions.Modifiers
@experimental
property holdUntilCrawlEnd
holdUntilCrawlEnd?: boolean;
When enabled, it will hold the first optimized deps results until all static imports are crawled on cold start. This avoids the need for full-page reloads when new dependencies are discovered and they trigger the generation of new common chunks. If all dependencies are found by the scanner plus the explicitly defined ones in
include
, it is better to disable this option to let the browser process more requests in parallel. trueModifiers
@experimental
property include
include?: string[];
Force optimize listed dependencies (must be resolvable import paths, cannot be globs).
property needsInterop
needsInterop?: string[];
Forces ESM interop when importing these dependencies. Some legacy packages advertise themselves as ESM but use
require
internallyModifiers
@experimental
property noDiscovery
noDiscovery?: boolean;
Automatic dependency discovery. When
noDiscovery
is true, only dependencies listed ininclude
will be optimized. The scanner isn't run for cold start in this case. CJS-only dependencies must be present ininclude
during dev. falseModifiers
@experimental
interface DepOptimizationMetadata
interface DepOptimizationMetadata {}
property browserHash
browserHash: string;
The browser hash is determined by the main hash plus additional dependencies discovered at runtime. This is used to invalidate browser requests to optimized deps.
property chunks
chunks: Record<string, OptimizedDepInfo>;
Metadata for non-entry optimized chunks and dynamic imports
property configHash
configHash: string;
This hash is determined by user config. This is checked on server startup to avoid unnecessary re-bundles.
property depInfoList
depInfoList: OptimizedDepInfo[];
OptimizedDepInfo list
property discovered
discovered: Record<string, OptimizedDepInfo>;
Metadata for each newly discovered dependency after processing
property hash
hash: string;
The main hash is determined by user config and dependency lockfiles. This is checked on server startup to avoid unnecessary re-bundles.
property lockfileHash
lockfileHash: string;
This hash is determined by dependency lockfiles. This is checked on server startup to avoid unnecessary re-bundles.
property optimized
optimized: Record<string, OptimizedDepInfo>;
Metadata for each already optimized dependency
interface DevEnvironmentContext
interface DevEnvironmentContext {}
property depsOptimizer
depsOptimizer?: DepsOptimizer;
property hot
hot: boolean;
property options
options?: EnvironmentOptions;
property remoteRunner
remoteRunner?: { inlineSourceMap?: boolean;};
property transport
transport?: HotChannel | WebSocketServer;
interface DevEnvironmentOptions
interface DevEnvironmentOptions {}
property createEnvironment
createEnvironment?: ( name: string, config: ResolvedConfig, context: CreateDevEnvironmentContext) => Promise<DevEnvironment> | DevEnvironment;
create the Dev Environment instance
property moduleRunnerTransform
moduleRunnerTransform?: boolean;
For environments associated with a module runner. By default it is true for the client environment and false for non-client environments. This option can also be used instead of the removed config.experimental.skipSsrTransform.
property preTransformRequests
preTransformRequests?: boolean;
Pre-transform known direct imports defaults to true for the client environment, false for the rest
property recoverable
recoverable?: boolean;
For environments that support a full-reload, like the client, we can short-circuit when restarting the server throwing early to stop processing current files. We avoided this for SSR requests. Maybe this is no longer needed.
Modifiers
@experimental
property sourcemap
sourcemap?: | boolean | { js?: boolean; css?: boolean; };
Enables sourcemaps during dev { js: true }
Modifiers
@experimental
property sourcemapIgnoreList
sourcemapIgnoreList?: | false | ((sourcePath: string, sourcemapPath: string) => boolean);
Whether or not to ignore-list source files in the dev server sourcemap, used to populate the [
x_google_ignoreList
source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).By default, it excludes all paths containing
node_modules
. You can passfalse
to disable this behavior, or, for full control, a function that takes the source path and sourcemap path and returns whether to ignore the source path.
property warmup
warmup?: string[];
Files to be pre-transformed. Supports glob patterns.
interface EnvironmentOptions
interface EnvironmentOptions extends SharedEnvironmentOptions {}
interface ErrorPayload
interface ErrorPayload {}
interface ESBuildOptions
interface ESBuildOptions extends esbuild_TransformOptions {}
interface ExperimentalOptions
interface ExperimentalOptions {}
property hmrPartialAccept
hmrPartialAccept?: boolean;
Enables support of HMR partial accept via
import.meta.hot.acceptExports
.false
Modifiers
@experimental
property importGlobRestoreExtension
importGlobRestoreExtension?: boolean;
Append fake
&lang.(ext)
when queries are specified, to preserve the file extension for following plugins to process.false
Modifiers
@experimental
property renderBuiltUrl
renderBuiltUrl?: RenderBuiltAssetUrl;
Allow finegrain control over assets and public files paths
Modifiers
@experimental
property skipSsrTransform
skipSsrTransform?: boolean;
Skips SSR transform to make it easier to use Vite with Node ESM loaders. Enabling this will break normal operation of Vite's SSR in development mode.
false
Modifiers
@experimental
interface FetchModuleOptions
interface FetchModuleOptions {}
property cached
cached?: boolean;
property inlineSourceMap
inlineSourceMap?: boolean;
property startOffset
startOffset?: number;
interface FileSystemServeOptions
interface FileSystemServeOptions {}
property allow
allow?: string[];
Restrict accessing files outside the allowed directories.
Accepts absolute path or a path relative to project root. Will try to search up for workspace root by default.
property deny
deny?: string[];
Restrict accessing files that matches the patterns.
This will have higher priority than
allow
. picomatch patterns are supported.['.env', '.env.*', '*.{crt,pem}', '**/.git/**']
property strict
strict?: boolean;
Strictly restrict file accessing outside of allowing paths.
Set to
false
to disable the warningtrue
interface FullReloadPayload
interface FullReloadPayload {}
interface HmrContext
interface HmrContext {}
interface HmrOptions
interface HmrOptions {}
interface HotChannel
interface HotChannel<Api = any> {}
property api
api?: Api;
method close
close: () => Promise<unknown> | void;
Disconnect all clients, called when server is closed or restarted.
method listen
listen: () => void;
Start listening for messages
method off
off: (event: string, listener: Function) => void;
Unregister event listener
method on
on: { <T extends string>(event: T, listener: HotChannelListener<T>): void; (event: 'connection', listener: () => void): void;};
Handle custom event emitted by
import.meta.hot.send
method send
send: (payload: HotPayload) => void;
Broadcast events to all clients
interface HotChannelClient
interface HotChannelClient {}
method send
send: (payload: HotPayload) => void;
interface HotUpdateOptions
interface HotUpdateOptions {}
property environment
environment: DevEnvironment;
Deprecated
use this.environment in the hotUpdate hook instead
property file
file: string;
property modules
modules: Array<EnvironmentModuleNode>;
property read
read: () => string | Promise<string>;
property server
server: ViteDevServer;
property timestamp
timestamp: number;
property type
type: 'create' | 'update' | 'delete';
interface HTMLOptions
interface HTMLOptions {}
property cspNonce
cspNonce?: string;
A nonce value placeholder that will be used when generating script/style tags.
Make sure that this placeholder will be replaced with a unique value for each request by the server.
interface HtmlTagDescriptor
interface HtmlTagDescriptor {}
interface ImportGlobFunction
interface ImportGlobFunction {}
call signature
< Eager extends boolean, As extends string, T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown>( glob: string | string[], options?: ImportGlobOptions<Eager, As>): (Eager extends true ? true : false) extends true ? Record<string, T> : Record<string, () => Promise<T>>;
Import a list of files with a glob pattern.
Overload 1: No generic provided, infer the type from
eager
andas
call signature
<M>(glob: string | string[], options?: ImportGlobOptions<false, string>): Record< string, () => Promise<M>>;
Import a list of files with a glob pattern.
Overload 2: Module generic provided, infer the type from
eager: false
call signature
<M>(glob: string | string[], options: ImportGlobOptions<true, string>): Record< string, M>;
Import a list of files with a glob pattern.
Overload 3: Module generic provided, infer the type from
eager: true
interface ImportGlobOptions
interface ImportGlobOptions<Eager extends boolean, AsType extends string> {}
property as
as?: AsType;
Import type for the import url.
Deprecated
Use
query
instead, e.g.as: 'url'
->query: '?url', import: 'default'
property eager
eager?: Eager;
Import as static or dynamic
false
property exhaustive
exhaustive?: boolean;
Search files also inside
node_modules/
and hidden directories (e.g..git/
). This might have impact on performance.false
property import
import?: string;
Import only the specific named export. Set to
default
to import the default export.
property query
query?: string | Record<string, string | number | boolean>;
Custom queries
interface IndexHtmlTransformContext
interface IndexHtmlTransformContext {}
interface InlineConfig
interface InlineConfig extends UserConfig {}
property configFile
configFile?: string | false;
property envFile
envFile?: false;
interface InternalResolveOptions
interface InternalResolveOptions extends Required<Omit<ResolveOptions, 'enableBuiltinNoExternalCheck'>>, ResolvePluginOptions {}
interface InvalidatePayload
interface InvalidatePayload {}
interface JsonOptions
interface JsonOptions {}
property namedExports
namedExports?: boolean;
Generate a named export for every property of the JSON object true
property stringify
stringify?: boolean | 'auto';
Generate performant output as JSON.parse("stringified").
When set to 'auto', the data will be stringified only if the data is bigger than 10kB. 'auto'
interface KnownAsTypeMap
interface KnownAsTypeMap {}
interface LegacyOptions
interface LegacyOptions {}
property proxySsrExternalModules
proxySsrExternalModules?: boolean;
In Vite 4, SSR-externalized modules (modules not bundled and loaded by Node.js at runtime) are implicitly proxied in dev to automatically handle
default
and__esModule
access. However, this does not correctly reflect how it works in the Node.js runtime, causing inconsistencies between dev and prod.In Vite 5, the proxy is removed so dev and prod are consistent, but if you still require the old behaviour, you can enable this option. If so, please leave your feedback at https://github.com/vitejs/vite/discussions/14697.
interface LibraryOptions
interface LibraryOptions {}
property cssFileName
cssFileName?: string;
The name of the CSS file output if the library imports CSS. Defaults to the same value as
build.lib.fileName
if it's set a string, otherwise it falls back to the name option of the project package.json.
property entry
entry: InputOption;
Path of library entry
property fileName
fileName?: string | ((format: ModuleFormat, entryName: string) => string);
The name of the package file output. The default file name is the name option of the project package.json. It can also be defined as a function taking the format as an argument.
property formats
formats?: LibraryFormats[];
Output bundle formats ['es', 'umd']
property name
name?: string;
The name of the exposed global variable. Required when the
formats
option includesumd
oriife
interface LogErrorOptions
interface LogErrorOptions extends LogOptions {}
property error
error?: Error | RollupError | null;