vite
- Version 6.0.11
- Published
- 2.83 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>; webSocketToken: string; } & 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>; webSocketToken: string; } & 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>; webSocketToken: string; } & 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 allowedHosts
allowedHosts?: string[] | true;
The hostnames that Vite is allowed to respond to.
localhost
and subdomains under.localhost
and all IP addresses are allowed by default. When using HTTPS, this check is skipped.If a string starts with
.
, it will allow that hostname without the.
and all subdomains under the hostname. For example,.example.com
will allowexample.com
,foo.example.com
, andfoo.bar.example.com
.If set to
true
, the server is allowed to respond to requests for any hosts. This is not recommended as it will be vulnerable to DNS rebinding attacks.
property cors
cors?: CorsOptions | boolean;
Configure CORS for the dev server. Uses https://github.com/expressjs/cors.
When enabling this option, **we recommend setting a specific value rather than
true
** to avoid exposing the source code to untrusted origins.Set to
true
to allow all methods from any origin, or configure separately using an object.false
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);
Configures the Access-Control-Allow-Origin CORS header.
**We recommend setting a specific value rather than
true
** to avoid exposing the source code to untrusted origins.
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.
property skipWebSocketTokenCheck
skipWebSocketTokenCheck?: boolean;
In Vite 6.0.8 and below, WebSocket server was able to connect from any web pages. However, that could be exploited by a malicious web page.
In Vite 6.0.9+, the WebSocket server now requires a token to connect from a web page. But this may break some plugins and frameworks that connects to the WebSocket server on their own. Enabling this option will make Vite skip the token check.
**We do not recommend enabling this option unless you are sure that you are fine with that security weakness.**
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;
interface Logger
interface Logger {}
property hasWarned
hasWarned: boolean;
method clearScreen
clearScreen: (type: LogType) => void;
method error
error: (msg: string, options?: LogErrorOptions) => void;
method hasErrorLogged
hasErrorLogged: (error: Error | RollupError) => boolean;
method info
info: (msg: string, options?: LogOptions) => void;
method warn
warn: (msg: string, options?: LogOptions) => void;
method warnOnce
warnOnce: (msg: string, options?: LogOptions) => void;
interface LoggerOptions
interface LoggerOptions {}
property allowClearScreen
allowClearScreen?: boolean;
property console
console?: Console;
property customLogger
customLogger?: Logger;
property prefix
prefix?: string;
interface LogOptions
interface LogOptions {}
property clear
clear?: boolean;
property environment
environment?: string;
property timestamp
timestamp?: boolean;
interface ManifestChunk
interface ManifestChunk {}
property assets
assets?: string[];
property css
css?: string[];
property dynamicImports
dynamicImports?: string[];
property file
file: string;
property imports
imports?: string[];
property isDynamicEntry
isDynamicEntry?: boolean;
property isEntry
isEntry?: boolean;
property name
name?: string;
property src
src?: string;
interface ModulePreloadOptions
interface ModulePreloadOptions {}
property polyfill
polyfill?: boolean;
Whether to inject a module preload polyfill. Note: does not apply to library mode. true
property resolveDependencies
resolveDependencies?: ResolveModulePreloadDependenciesFn;
Resolve the list of dependencies to preload for a given dynamic import
Modifiers
@experimental
interface ModuleRunnerTransformOptions
interface ModuleRunnerTransformOptions {}
property json
json?: { stringify?: boolean;};
interface OptimizedDepInfo
interface OptimizedDepInfo {}
property browserHash
browserHash?: string;
property exportsData
exportsData?: Promise<ExportsData>;
ExportData cache, discovered deps will parse the src entry to get exports data used both to define if interop is needed and when pre-bundling
property file
file: string;
property fileHash
fileHash?: string;
property id
id: string;
property needsInterop
needsInterop?: boolean;
property processing
processing?: Promise<void>;
During optimization, ids can still be resolved to their final location but the bundles may not yet be saved to disk
property src
src?: string;
interface Plugin
interface Plugin<A = any> extends rollup.Plugin<A> {}
There are two types of plugins in Vite. App plugins and environment plugins. Environment Plugins are defined by a constructor function that will be called once per each environment allowing users to have completely different plugins for each of them. The constructor gets the resolved environment after the server and builder has already been created simplifying config access and cache management for for environment specific plugins. Environment Plugins are closer to regular rollup plugins. They can't define app level hooks (like config, configResolved, configureServer, etc).
property apply
apply?: | 'serve' | 'build' | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
Apply the plugin only for serve or build, or on certain conditions.
property applyToEnvironment
applyToEnvironment?: ( environment: PartialEnvironment) => boolean | Promise<boolean> | PluginOption;
Define environments where this plugin should be active By default, the plugin is active in all environments
Modifiers
@experimental
property config
config?: ObjectHook< ( this: void, config: UserConfig, env: ConfigEnv ) => | Omit<UserConfig, 'plugins'> | null | void | Promise<Omit<UserConfig, 'plugins'> | null | void>>;
Modify vite config before it's resolved. The hook can either mutate the passed-in config directly, or return a partial config object that will be deeply merged into existing config.
Note: User plugins are resolved before running this hook so injecting other plugins inside the
config
hook will have no effect.
property configEnvironment
configEnvironment?: ObjectHook< ( this: void, name: string, config: EnvironmentOptions, env: ConfigEnv & { /** * Whether this environment is SSR environment and `ssr.target` is set to `'webworker'`. * Only intended to be used for backward compatibility. */ isSsrTargetWebworker?: boolean; } ) => | EnvironmentOptions | null | void | Promise<EnvironmentOptions | null | void>>;
Modify environment configs before it's resolved. The hook can either mutate the passed-in environment config directly, or return a partial config object that will be deeply merged into existing config. This hook is called for each environment with a partially resolved environment config that already accounts for the default environment config values set at the root level. If plugins need to modify the config of a given environment, they should do it in this hook instead of the config hook. Leaving the config hook only for modifying the root default environment config.
property configResolved
configResolved?: ObjectHook< (this: void, config: ResolvedConfig) => void | Promise<void>>;
Use this hook to read and store the final resolved vite config.
property configurePreviewServer
configurePreviewServer?: ObjectHook<PreviewServerHook>;
Configure the preview server. The hook receives the PreviewServer instance. This can also be used to store a reference to the server for use in other hooks.
The hooks are called before other middlewares are applied. A hook can return a post hook that will be called after other middlewares are applied. Hooks can be async functions and will be called in series.
property configureServer
configureServer?: ObjectHook<ServerHook>;
Configure the vite server. The hook receives the ViteDevServer instance. This can also be used to store a reference to the server for use in other hooks.
The hooks will be called before internal middlewares are applied. A hook can return a post hook that will be called after internal middlewares are applied. Hook can be async functions and will be called in series.
property enforce
enforce?: 'pre' | 'post';
Enforce plugin invocation tier similar to webpack loaders. Hooks ordering is still subject to the
order
property in the hook object.Plugin invocation order: - alias resolution -
enforce: 'pre'
plugins - vite core plugins - normal plugins - vite build plugins -enforce: 'post'
plugins - vite build post plugins
property handleHotUpdate
handleHotUpdate?: ObjectHook< ( this: void, ctx: HmrContext ) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>>;
Perform custom handling of HMR updates. The handler receives a context containing changed filename, timestamp, a list of modules affected by the file change, and the dev server instance.
- The hook can return a filtered list of modules to narrow down the update. e.g. for a Vue SFC, we can narrow down the part to update by comparing the descriptors.
- The hook can also return an empty array and then perform custom updates by sending a custom hmr payload via server.ws.send().
- If the hook doesn't return a value, the hmr update will be performed as normal.
property hotUpdate
hotUpdate?: ObjectHook< ( this: HotUpdatePluginContext, options: HotUpdateOptions ) => | Array<EnvironmentModuleNode> | void | Promise<Array<EnvironmentModuleNode> | void>>;
Perform custom handling of HMR updates. The handler receives an options containing changed filename, timestamp, a list of modules affected by the file change, and the dev server instance.
- The hook can return a filtered list of modules to narrow down the update. e.g. for a Vue SFC, we can narrow down the part to update by comparing the descriptors.
- The hook can also return an empty array and then perform custom updates by sending a custom hmr payload via environment.hot.send().
- If the hook doesn't return a value, the hmr update will be performed as normal.
property load
load?: ObjectHook< ( this: PluginContext, id: string, options?: { ssr?: boolean; } ) => Promise<LoadResult> | LoadResult>;
property perEnvironmentStartEndDuringDev
perEnvironmentStartEndDuringDev?: boolean;
Opt-in this plugin into per-environment buildStart and buildEnd during dev. For backward-compatibility, the buildStart hook is called only once during dev, for the client environment. Plugins can opt-in to be called per-environment, aligning with the build hook behavior.
Modifiers
@experimental
property resolveId
resolveId?: ObjectHook< ( this: ResolveIdPluginContext, source: string, importer: string | undefined, options: { attributes: Record<string, string>; custom?: CustomPluginOptions; ssr?: boolean; isEntry: boolean; } ) => Promise<ResolveIdResult> | ResolveIdResult>;
extend hooks with ssr flag
property sharedDuringBuild
sharedDuringBuild?: boolean;
Opt-in this plugin into the shared plugins pipeline. For backward-compatibility, plugins are re-recreated for each environment during
vite build --app
We have an opt-in per plugin, and a generalbuilder.sharedPlugins
In a future major, we'll flip the default to be shared by defaultModifiers
@experimental
property transform
transform?: ObjectHook< ( this: TransformPluginContext, code: string, id: string, options?: { ssr?: boolean; } ) => Promise<rollup.TransformResult> | rollup.TransformResult>;
property transformIndexHtml
transformIndexHtml?: IndexHtmlTransform;
Transform index.html. The hook receives the following arguments:
- html: string - ctx?: vite.ServerContext (only present during serve) - bundle?: rollup.OutputBundle (only present during build)
It can either return a transformed string, or a list of html tag descriptors that will be injected into the
<head>
or<body>
.By default the transform is applied **after** vite's internal html transform. If you need to apply the transform before vite, use an object:
{ order: 'pre', handler: hook }
interface PluginHookUtils
interface PluginHookUtils {}
property getSortedPluginHooks
getSortedPluginHooks: <K extends keyof Plugin>( hookName: K) => NonNullable<HookHandler<Plugin[K]>>[];
property getSortedPlugins
getSortedPlugins: <K extends keyof Plugin>( hookName: K) => PluginWithRequiredHook<K>[];
interface PreprocessCSSResult
interface PreprocessCSSResult {}
interface PreviewOptions
interface PreviewOptions extends CommonServerOptions {}
interface PreviewServer
interface PreviewServer {}
property config
config: ResolvedConfig;
The resolved vite config object
property httpServer
httpServer: HttpServer;
native Node http server instance
property middlewares
middlewares: Connect.Server;
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
property resolvedUrls
resolvedUrls: ResolvedServerUrls | null;
The resolved urls Vite prints on the CLI (URL-encoded). Returns
null
if the server is not listening on any port.
method bindCLIShortcuts
bindCLIShortcuts: (options?: BindCLIShortcutsOptions<PreviewServer>) => void;
Bind CLI shortcuts
method close
close: () => Promise<void>;
Stop the server.
method printUrls
printUrls: () => void;
Print server urls
interface ProxyOptions
interface ProxyOptions extends HttpProxy.ServerOptions {}
property bypass
bypass?: ( req: http.IncomingMessage, /** undefined for WebSocket upgrade requests */ res: http.ServerResponse | undefined, options: ProxyOptions) => void | null | undefined | false | string;
webpack-dev-server style bypass function
property configure
configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
configure the proxy server (e.g. listen to events)
property rewrite
rewrite?: (path: string) => string;
rewrite path
property rewriteWsOrigin
rewriteWsOrigin?: boolean | undefined;
rewrite the Origin header of a WebSocket request to match the target
**Exercise caution as rewriting the Origin can leave the proxying open to [CSRF attacks](https://owasp.org/www-community/attacks/csrf).**
interface PrunePayload
interface PrunePayload {}
interface ResolvedBuildEnvironmentOptions
interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {}
property modulePreload
modulePreload: false | ResolvedModulePreloadOptions;
interface ResolvedBuildOptions
interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {}
property modulePreload
modulePreload: false | ResolvedModulePreloadOptions;
interface ResolvedModulePreloadOptions
interface ResolvedModulePreloadOptions {}
property polyfill
polyfill: boolean;
property resolveDependencies
resolveDependencies?: ResolveModulePreloadDependenciesFn;
interface ResolvedPreviewOptions
interface ResolvedPreviewOptions extends RequiredExceptFor<PreviewOptions, 'host' | 'https' | 'proxy'> {}
interface ResolvedServerOptions
interface ResolvedServerOptions extends Omit< RequiredExceptFor< ServerOptions, | 'host' | 'https' | 'proxy' | 'hmr' | 'ws' | 'watch' | 'origin' | 'hotUpdateEnvironments' >, 'fs' | 'middlewareMode' | 'sourcemapIgnoreList' > {}
property fs
fs: Required<FileSystemServeOptions>;
property middlewareMode
middlewareMode: NonNullable<ServerOptions['middlewareMode']>;
property sourcemapIgnoreList
sourcemapIgnoreList: Exclude< ServerOptions['sourcemapIgnoreList'], false | undefined>;
interface ResolvedServerUrls
interface ResolvedServerUrls {}
interface ResolvedSSROptions
interface ResolvedSSROptions extends SSROptions {}
property optimizeDeps
optimizeDeps: SsrDepOptimizationConfig;
property target
target: SSRTarget;
interface ResolvedWorkerOptions
interface ResolvedWorkerOptions {}
property format
format: 'es' | 'iife';
property plugins
plugins: (bundleChain: string[]) => Promise<ResolvedConfig>;
property rollupOptions
rollupOptions: RollupOptions;
interface ResolveOptions
interface ResolveOptions extends EnvironmentResolveOptions {}
property preserveSymlinks
preserveSymlinks?: boolean;
false
interface ResolverObject
interface ResolverObject {}
property buildStart
buildStart?: PluginHooks['buildStart'];
property resolveId
resolveId: ResolverFunction;
interface RollupCommonJSOptions
interface RollupCommonJSOptions {}
property defaultIsModuleExports
defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto');
"auto"
property dynamicRequireRoot
dynamicRequireRoot?: string;
To avoid long paths when using the
dynamicRequireTargets
option, you can use this option to specify a directory that is a common parent for all files that use dynamic require statements. Using a directory higher up such as/
may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your home directory name. By default, it uses the current working directory.
property dynamicRequireTargets
dynamicRequireTargets?: string | ReadonlyArray<string>;
Some modules contain dynamic
require
calls, or require modules that contain circular dependencies, which are not handled well by static imports. Including those modules asdynamicRequireTargets
will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic dependencies. It also enablesstrictRequires
for those modules.Note: In extreme cases, this feature may result in some paths being rendered as absolute in the final bundle. The plugin tries to avoid exposing paths from the local machine, but if you are
dynamicRequirePaths
with paths that are far away from your project's folder, that may require replacing strings like"/Users/John/Desktop/foo-project/"
->"/"
.
property esmExternals
esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean);
Controls how to render imports from external dependencies. By default, this plugin assumes that all external dependencies are CommonJS. This means they are rendered as default imports to be compatible with e.g. NodeJS where ES modules can only import a default export from a CommonJS dependency.
If you set
esmExternals
totrue
, this plugin assumes that all external dependencies are ES modules and respect therequireReturnsDefault
option. If that option is not set, they will be rendered as namespace imports.You can also supply an array of ids to be treated as ES modules, or a function that will be passed each external id to determine whether it is an ES module. false
property exclude
exclude?: string | RegExp | readonly (string | RegExp)[];
A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should _ignore_. By default, all files with extensions other than those in
extensions
or".cjs"
are ignored, but you can exclude additional files. See also theinclude
option. undefined
property extensions
extensions?: ReadonlyArray<string>;
For extensionless imports, search for extensions other than .js in the order specified. Note that you need to make sure that non-JavaScript files are transpiled by another plugin first. [ '.js' ]
property ignore
ignore?: ReadonlyArray<string> | ((id: string) => boolean);
Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or a
id => boolean
function. []
property ignoreDynamicRequires
ignoreDynamicRequires?: boolean;
Some
require
calls cannot be resolved statically to be translated to imports. When this option is set tofalse
, the generated code will either directly throw an error when such a call is encountered or, whendynamicRequireTargets
is used, when such a call cannot be resolved with a configured dynamic require target. Setting this option totrue
will instead leave therequire
call in the code or use it as a fallback fordynamicRequireTargets
. false
property ignoreGlobal
ignoreGlobal?: boolean;
If true then uses of
global
won't be dealt with by this plugin false
property ignoreTryCatch
ignoreTryCatch?: | boolean | 'remove' | ReadonlyArray<string> | ((id: string) => boolean | 'remove');
In most cases, where
require
calls are inside atry-catch
clause, they should be left unconverted as it requires an optional dependency that may or may not be installed beside the rolled up package. Due to the conversion ofrequire
to a staticimport
- the call is hoisted to the top of the file, outside thetry-catch
clause.-
true
: Default. Allrequire
calls inside atry
will be left unconverted. -false
: Allrequire
calls inside atry
will be converted as if thetry-catch
clause is not there. -remove
: Remove allrequire
calls from inside anytry
block. -string[]
: Pass an array containing the IDs to left unconverted. -((id: string) => boolean|'remove')
: Pass a function that controls individual IDs.true
property include
include?: string | RegExp | readonly (string | RegExp)[];
A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. By default, all files with extension
".cjs"
or those inextensions
are included, but you can narrow this list by only including specific files. These files will be analyzed and transpiled if either the analysis does not find ES module specific statements ortransformMixedEsModules
istrue
. undefined
property requireReturnsDefault
requireReturnsDefault?: | boolean | 'auto' | 'preferred' | 'namespace' | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace');
Controls what is returned when requiring an ES module from a CommonJS file. When using the
esmExternals
option, this will also apply to external modules. By default, this plugin will render those imports as namespace imports i.e.// inputconst foo = require('foo');// outputimport * as foo from 'foo';However, there are some situations where this may not be desired. For these situations, you can change Rollup's behaviour either globally or per module. To change it globally, set the
requireReturnsDefault
option to one of the following values:-
false
: This is the default, requiring an ES module returns its namespace. This is the only option that will also add a marker__esModule: true
to the namespace to support interop patterns in CommonJS modules that are transpiled ES modules. -"namespace"
: Likefalse
, requiring an ES module returns its namespace, but the plugin does not add the__esModule
marker and thus creates more efficient code. For external dependencies when usingesmExternals: true
, no additional interop code is generated. -"auto"
: This is complementary to howoutput.exports: "auto"
works in Rollup: If a module has a default export and no named exports, requiring that module returns the default export. In all other cases, the namespace is returned. For external dependencies when usingesmExternals: true
, a corresponding interop helper is added. -"preferred"
: If a module has a default export, requiring that module always returns the default export, no matter whether additional named exports exist. This is similar to how previous versions of this plugin worked. Again for external dependencies when usingesmExternals: true
, an interop helper is added. -true
: This will always try to return the default export on require without checking if it actually exists. This can throw at build time if there is no default export. This is how external dependencies are handled whenesmExternals
is not used. The advantage over the other options is that, likefalse
, this does not add an interop helper for external dependencies, keeping the code lean.To change this for individual modules, you can supply a function for
requireReturnsDefault
instead. This function will then be called once for each required ES module or external dependency with the corresponding id and allows you to return different values for different modules. false
property sourceMap
sourceMap?: boolean;
If false, skips source map generation for CommonJS modules. This will improve performance. true
property strictRequires
strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[];
By default, this plugin will try to hoist
require
statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the order of side effects like log statements may change. But it is especially problematic when there are circularrequire
calls between CommonJS modules as those often rely on the lazy execution of nestedrequire
calls.Setting this option to
true
will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. Note that this can have an impact on the size and performance of the generated code.The default value of
"auto"
will only wrap CommonJS files when they are part of a CommonJS dependency cycle, e.g. an index file that is required by many of its dependencies. All other CommonJS files are hoisted. This is the recommended setting for most code bases.false
will entirely prevent wrapping and hoist all files. This may still work depending on the nature of cyclic dependencies but will often cause problems.You can also provide a minimatch pattern, or array of patterns, to only specify a subset of files which should be wrapped in functions for proper
require
semantics."debug"
works like"auto"
but after bundling, it will display a warning containing a list of ids that have been wrapped which can be used as minimatch pattern for fine-tuning. "auto"
property transformMixedEsModules
transformMixedEsModules?: boolean;
Instructs the plugin whether to enable mixed module transformations. This is useful in scenarios with modules that contain a mix of ES
import
statements and CommonJSrequire
expressions. Set totrue
ifrequire
calls should be transformed to imports in mixed modules, orfalse
if therequire
expressions should survive the transformation. The latter can be important if the code contains environment detection, or you are coding for an environment with special treatment forrequire
calls such as ElectronJS. See also theignore
option. false
interface RollupDynamicImportVarsOptions
interface RollupDynamicImportVarsOptions {}
property exclude
exclude?: string | RegExp | (string | RegExp)[];
Files to exclude in this plugin (default none). []
property include
include?: string | RegExp | (string | RegExp)[];
Files to include in this plugin (default all). []
property warnOnError
warnOnError?: boolean;
By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched. false
interface RunnableDevEnvironmentContext
interface RunnableDevEnvironmentContext extends Omit<DevEnvironmentContext, 'hot'> {}
property hot
hot?: boolean;
property runner
runner?: ( environment: RunnableDevEnvironment, options?: ServerModuleRunnerOptions) => ModuleRunner;
property runnerOptions
runnerOptions?: ServerModuleRunnerOptions;
interface SendOptions
interface SendOptions {}
property cacheControl
cacheControl?: string;
property etag
etag?: string;
property headers
headers?: OutgoingHttpHeaders;
property map
map?: | SourceMap | { mappings: ''; } | null;
interface ServerModuleRunnerOptions
interface ServerModuleRunnerOptions extends Omit< ModuleRunnerOptions, 'root' | 'fetchModule' | 'hmr' | 'transport' > {}
Modifiers
@experimental
interface ServerOptions
interface ServerOptions extends CommonServerOptions {}
property fs
fs?: FileSystemServeOptions;
Options for files served via '/@fs/'.
property hmr
hmr?: HmrOptions | boolean;
Configure HMR-specific options (port, host, path & protocol)
property hotUpdateEnvironments
hotUpdateEnvironments?: ( server: ViteDevServer, hmr: (environment: DevEnvironment) => Promise<void>) => Promise<void>;
Run HMR tasks, by default the HMR propagation is done in parallel for all environments
Modifiers
@experimental
property middlewareMode
middlewareMode?: | boolean | { /** * Parent server instance to attach to * * This is needed to proxy WebSocket connections to the parent server. */ server: HttpServer; };
Create Vite dev server to be used as a middleware in an existing server false
property origin
origin?: string;
Origin for the generated asset URLs.
Example 1
http://127.0.0.1:8080
property perEnvironmentStartEndDuringDev
perEnvironmentStartEndDuringDev?: boolean;
Backward compatibility. The buildStart and buildEnd hooks were called only once for all environments. This option enables per-environment buildStart and buildEnd hooks. false
Modifiers
@experimental
property preTransformRequests
preTransformRequests?: boolean;
Pre-transform known direct imports true
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?: { /** * The files to be transformed and used on the client-side. Supports glob patterns. */ clientFiles?: string[]; /** * The files to be transformed and used in SSR. Supports glob patterns. */ ssrFiles?: string[];};
Warm-up files to transform and cache the results in advance. This improves the initial page load during server starts and prevents transform waterfalls.
property watch
watch?: WatchOptions | null;
chokidar watch options or null to disable FS watching https://github.com/paulmillr/chokidar/tree/3.6.0#api
property ws
ws?: false;
Do not start the websocket connection.
Modifiers
@experimental
interface SSROptions
interface SSROptions {}
property external
external?: string[] | true;
property noExternal
noExternal?: string | RegExp | (string | RegExp)[] | true;
property optimizeDeps
optimizeDeps?: SsrDepOptimizationConfig;
Control over which dependencies are optimized during SSR and esbuild options During build: no external CJS dependencies are optimized by default During dev: explicit no external CJS dependencies are optimized by default
Modifiers
@experimental
property resolve
resolve?: { /** * Conditions that are used in the plugin pipeline. The default value is the root config's `resolve.conditions`. * * Use this to override the default ssr conditions for the ssr build. * * @default rootConfig.resolve.conditions */ conditions?: string[]; /** * Conditions that are used during ssr import (including `ssrLoadModule`) of externalized dependencies. * * @default [] */ externalConditions?: string[]; mainFields?: string[];};
property target
target?: SSRTarget;
Define the target for the ssr build. The browser field in package.json is ignored for node but used if webworker is the target This option will be removed in a future major version 'node'
interface TerserOptions
interface TerserOptions extends Terser.MinifyOptions {}
property maxWorkers
maxWorkers?: number;
Vite-specific option to specify the max number of workers to spawn when minifying files with terser.
number of CPUs minus 1
interface TransformOptions
interface TransformOptions {}
property ssr
ssr?: boolean;
Deprecated
inferred from environment
interface TransformResult
interface TransformResult {}
interface Update
interface Update {}
property acceptedPath
acceptedPath: string;
property path
path: string;
property timestamp
timestamp: number;
property type
type: 'js-update' | 'css-update';
interface UpdatePayload
interface UpdatePayload {}
interface UserConfig
interface UserConfig extends DefaultEnvironmentOptions {}
property appType
appType?: AppType;
Whether your application is a Single Page Application (SPA), a Multi-Page Application (MPA), or Custom Application (SSR and frameworks with custom HTML handling) 'spa'
property assetsInclude
assetsInclude?: string | RegExp | (string | RegExp)[];
Specify additional picomatch patterns to be treated as static assets.
property base
base?: string;
Base public path when served in development or production. '/'
property builder
builder?: BuilderOptions;
Builder specific options
Modifiers
@experimental
property cacheDir
cacheDir?: string;
Directory to save cache files. Files in this directory are pre-bundled deps or some other cache files that generated by vite, which can improve the performance. You can use
--force
flag or manually delete the directory to regenerate the cache files. The value can be either an absolute file system path or a path relative to project root. Default to.vite
when nopackage.json
is detected. 'node_modules/.vite'
property clearScreen
clearScreen?: boolean;
true
property css
css?: CSSOptions;
CSS related options (preprocessors and CSS modules)
property customLogger
customLogger?: Logger;
Custom logger.
property envDir
envDir?: string;
Environment files directory. Can be an absolute path, or a path relative from root. root
property environments
environments?: Record<string, EnvironmentOptions>;
Environment overrides
property envPrefix
envPrefix?: string | string[];
Env variables starts with
envPrefix
will be exposed to your client source code via import.meta.env. 'VITE_'
property esbuild
esbuild?: ESBuildOptions | false;
Transform options to pass to esbuild. Or set to
false
to disable esbuild.
property experimental
experimental?: ExperimentalOptions;
Experimental features
Features under this field could change in the future and might NOT follow semver. Please be careful and always pin Vite's version when using them.
Modifiers
@experimental
property future
future?: FutureOptions;
Options to opt-in to future behavior
property html
html?: HTMLOptions;
HTML related options
property json
json?: JsonOptions;
JSON loading options
property legacy
legacy?: LegacyOptions;
Legacy options
Features under this field only follow semver for patches, they could be removed in a future minor version. Please always pin Vite's version to a minor when using them.
property logLevel
logLevel?: LogLevel;
Log level. 'info'
property mode
mode?: string;
Explicitly set a mode to run in. This will override the default mode for each command, and can be overridden by the command line --mode option.
property optimizeDeps
optimizeDeps?: DepOptimizationOptions;
Dep optimization options
property plugins
plugins?: PluginOption[];
Array of vite plugins to use.
property preview
preview?: PreviewOptions;
Preview specific options, e.g. host, port, https...
property publicDir
publicDir?: string | false;
Directory to serve as plain static assets. Files in this directory are served and copied to build dist dir as-is without transform. The value can be either an absolute file system path or a path relative to project root.
Set to
false
or an empty string to disable copied static assets to build dist dir. 'public'
property root
root?: string;
Project root directory. Can be an absolute path, or a path relative from the location of the config file itself. process.cwd()
property server
server?: ServerOptions;
Server specific options, e.g. host, port, https...
property ssr
ssr?: SSROptions;
SSR specific options We could make SSROptions be a EnvironmentOptions if we can abstract external/noExternal for environments in general.
property worker
worker?: { /** * Output format for worker bundle * @default 'iife' */ format?: 'es' | 'iife'; /** * Vite plugins that apply to worker bundle. The plugins returned by this function * should be new instances every time it is called, because they are used for each * rollup worker bundling process. */ plugins?: () => PluginOption[]; /** * Rollup options to build worker bundle */ rollupOptions?: Omit< RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures' >;};
Worker bundle options
interface ViteBuilder
interface ViteBuilder {}
property config
config: ResolvedConfig;
property environments
environments: Record<string, BuildEnvironment>;
method build
build: ( environment: BuildEnvironment) => Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
method buildApp
buildApp: () => Promise<void>;
interface ViteDevServer
interface ViteDevServer {}
property config
config: ResolvedConfig;
The resolved vite config object
property environments
environments: Record<'client' | 'ssr' | (string & {}), DevEnvironment>;
Module execution environments attached to the Vite server.
property hot
hot: HotBroadcaster;
HMR broadcaster that can be used to send custom HMR messages to the client
Always sends a message to at least a WebSocket client. Any third party can add a channel to the broadcaster to process messages
property httpServer
httpServer: HttpServer | null;
native Node http server instance will be null in middleware mode
property middlewares
middlewares: Connect.Server;
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
property moduleGraph
moduleGraph: ModuleGraph;
Module graph that tracks the import relationships, url to file mapping and hmr state.
property pluginContainer
pluginContainer: PluginContainer;
Rollup plugin container that can run plugin hooks on a given file
property resolvedUrls
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.
property waitForRequestsIdle
waitForRequestsIdle: (ignoredId?: string) => Promise<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.
property watcher
watcher: FSWatcher;
Chokidar watcher instance. If
config.server.watch
is set tonull
, it will not watch any files and callingadd
orunwatch
will have no effect. https://github.com/paulmillr/chokidar/tree/3.6.0#api
property ws
ws: WebSocketServer;
web socket server with
send(payload)
method
method bindCLIShortcuts
bindCLIShortcuts: (options?: BindCLIShortcutsOptions<ViteDevServer>) => void;
Bind CLI shortcuts
method close
close: () => Promise<void>;
Stop the server.
method listen
listen: (port?: number, isRestart?: boolean) => Promise<ViteDevServer>;
Start the server.
method openBrowser
openBrowser: () => void;
Open browser
method printUrls
printUrls: () => void;
Print server urls
method reloadModule
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. Ifhmr
is false, this is a no-op.
method restart
restart: (forceOptimize?: boolean) => Promise<void>;
Restart the server.
Parameter forceOptimize
force the optimizer to re-bundle, same as --force cli flag
method ssrFixStacktrace
ssrFixStacktrace: (e: Error) => void;
Mutates the given SSR error by rewriting the stacktrace
method ssrLoadModule
ssrLoadModule: ( url: string, opts?: { fixStacktrace?: boolean }) => Promise<Record<string, any>>;
Load a given URL as an instantiated module for SSR.
method ssrRewriteStacktrace
ssrRewriteStacktrace: (stack: string) => string;
Returns a fixed version of the given stack
method ssrTransform
ssrTransform: ( code: string, inMap: SourceMap | { mappings: '' } | null, url: string, originalCode?: string) => Promise<TransformResult | null>;
Transform module code into SSR format.
method transformIndexHtml
transformIndexHtml: ( url: string, html: string, originalUrl?: string) => Promise<string>;
Apply vite built-in HTML transforms and any plugin HTML transforms.
method transformRequest
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.
method warmupRequest
warmupRequest: (url: string, options?: TransformOptions) => Promise<void>;
Same as
transformRequest
but only warm up the URLs so the next request will already be cached. The function will never throw as it handles and reports errors internally.
interface WatchOptions
interface WatchOptions {}
property alwaysStat
alwaysStat?: boolean;
If relying upon the [
fs.Stats
](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that may get passed withadd
,addDir
, andchange
events, set this totrue
to ensure it is provided even in cases where it wasn't already available from the underlying watch events.
property atomic
atomic?: boolean | number;
true
ifuseFsEvents
andusePolling
arefalse
. Automatically filters out artifacts that occur when using editors that use "atomic writes" instead of writing directly to the source file. If a file is re-added within 100 ms of being deleted, Chokidar emits achange
event rather thanunlink
thenadd
. If the default of 100 ms does not work well for you, you can override it by settingatomic
to a custom value, in milliseconds.
property awaitWriteFinish
awaitWriteFinish?: AwaitWriteFinishOptions | boolean;
can be set to an object in order to adjust timing params:
property binaryInterval
binaryInterval?: number;
Interval of file system polling for binary files. ([see list of binary extensions](https://gi thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
property cwd
cwd?: string;
The base directory from which watch
paths
are to be derived. Paths emitted with events will be relative to this.
property depth
depth?: number;
If set, limits how many levels of subdirectories will be traversed.
property disableGlobbing
disableGlobbing?: boolean;
If set to true then the strings passed to .watch() and .add() are treated as literal path names, even if they look like globs.
false
property followSymlinks
followSymlinks?: boolean;
When
false
, only the symlinks themselves will be watched for changes instead of following the link references and bubbling events through the link's path.
property ignored
ignored?: AnymatchMatcher;
([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to be ignored. The whole relative or absolute path is tested, not just filename. If a function with two arguments is provided, it gets called twice per path - once with a single argument (the path), second time with two arguments (the path and the [
fs.Stats
](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
property ignoreInitial
ignoreInitial?: boolean;
If set to
false
thenadd
/addDir
events are also emitted for matching paths while instantiating the watching as chokidar discovers these file paths (before theready
event).
property ignorePermissionErrors
ignorePermissionErrors?: boolean;
Indicates whether to watch files that don't have read permissions if possible. If watching fails due to
EPERM
orEACCES
with this set totrue
, the errors will be suppressed silently.
property interval
interval?: number;
Interval of file system polling.
property persistent
persistent?: boolean;
Indicates whether the process should continue to run as long as files are being watched. If set to
false
when usingfsevents
to watch, no more events will be emitted afterready
, even if the process continues to run.
property useFsEvents
useFsEvents?: boolean;
Whether to use the
fsevents
watching interface if available. When set totrue
explicitly andfsevents
is available this supersedes theusePolling
setting. When set tofalse
on OS X,usePolling: true
becomes the default.
property usePolling
usePolling?: boolean;
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU utilization, consider setting this to
false
. It is typically necessary to **set this totrue
to successfully watch files over a network**, and it may be necessary to successfully watch files in other non-standard situations. Setting totrue
explicitly on OS X overrides theuseFsEvents
default.
interface WebSocketAlias
interface WebSocketAlias extends WebSocket {}
interface WebSocketClient
interface WebSocketClient extends NormalizedHotChannelClient {}
property socket
socket: WebSocket;
The raw WebSocket instance
interface WebSocketServer
interface WebSocketServer extends NormalizedHotChannel {}
property [isWebSocketServer]
[isWebSocketServer]: true;
property clients
clients: Set<WebSocketClient>;
Get all connected clients.
property off
off: WebSocket.Server['off'] & { (event: string, listener: Function): void;};
Unregister event listener.
property on
on: WebSocket.Server['on'] & { <T extends string>( event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>> ): void;};
Handle custom event emitted by
import.meta.hot.send
method close
close: () => Promise<void>;
Disconnect all clients and terminate the server.
method listen
listen: () => void;
Listen on port and host
Type Aliases
type AliasOptions
type AliasOptions = readonly Alias[] | { [find: string]: string };
Specifies an
Object
, or anArray
ofObject
, which defines aliases used to replace values inimport
orrequire
statements. With either format, the order of the entries is important, in that the first defined rules are applied first.This is passed to @rollup/plugin-alias as the "entries" field https://github.com/rollup/plugins/tree/master/packages/alias#entries
type AnymatchFn
type AnymatchFn = (testString: string) => boolean;
type AnymatchPattern
type AnymatchPattern = string | RegExp | AnymatchFn;
type AppType
type AppType = 'spa' | 'mpa' | 'custom';
spa: include SPA fallback middleware and configure sirv with
single: true
in previewmpa: only include non-SPA HTML middlewares
custom: don't include HTML middlewares
type BindCLIShortcutsOptions
type BindCLIShortcutsOptions<Server = ViteDevServer | PreviewServer> = { /** * Print a one-line shortcuts "help" hint to the terminal */ print?: boolean; /** * Custom shortcuts to run when a key is pressed. These shortcuts take priority * over the default shortcuts if they have the same keys (except the `h` key). * To disable a default shortcut, define the same key but with `action: undefined`. */ customShortcuts?: CLIShortcut<Server>[];};
type BuildOptions
type BuildOptions = BuildEnvironmentOptions;
type CLIShortcut
type CLIShortcut<Server = ViteDevServer | PreviewServer> = { key: string; description: string; action?(server: Server): void | Promise<void>;};
type CorsOrigin
type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
type DepOptimizationOptions
type DepOptimizationOptions = DepOptimizationConfig & { /** * By default, Vite will crawl your `index.html` to detect dependencies that * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite * will crawl those entry points instead. * * If neither of these fit your needs, you can specify custom entries using * this option - the value should be a tinyglobby pattern or array of patterns * (https://github.com/SuperchupuDev/tinyglobby) that are relative from * vite project root. This will overwrite default entries inference. */ entries?: string | string[]; /** * Force dep pre-optimization regardless of whether deps have changed. * @experimental */ force?: boolean;};
type Environment
type Environment = DevEnvironment | BuildEnvironment | UnknownEnvironment;
type ESBuildTransformResult
type ESBuildTransformResult = Omit<esbuild_TransformResult, 'map'> & { map: SourceMap;};
type ExportsData
type ExportsData = { hasModuleSyntax: boolean; exports: readonly string[]; jsxLoader?: boolean;};
type FilterPattern
type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
Inlined to keep
@rollup/pluginutils
in devDependencies
type GeneralImportGlobOptions
type GeneralImportGlobOptions = ImportGlobOptions<boolean, string>;
type HMRBroadcaster
type HMRBroadcaster = HotBroadcaster;
Deprecated
use
environment.hot
instead
type HMRBroadcasterClient
type HMRBroadcasterClient = HotChannelClient;
Deprecated
use
HotChannelClient
instead
type HMRChannel
type HMRChannel = HotChannel;
Deprecated
use
HotChannel
instead
type HMRPayload
type HMRPayload = HotPayload;
Deprecated
use HotPayload
type HookHandler
type HookHandler<T> = T extends ObjectHook<infer H> ? H : T;
type HotChannelListener
type HotChannelListener<T extends string = string> = ( data: InferCustomEventPayload<T>, client: HotChannelClient) => void;
type HotPayload
type HotPayload = | ConnectedPayload | PingPayload | UpdatePayload | FullReloadPayload | CustomPayload | ErrorPayload | PrunePayload;
type HttpServer
type HttpServer = http.Server | Http2SecureServer;
type IndexHtmlTransform
type IndexHtmlTransform = | IndexHtmlTransformHook | { order?: 'pre' | 'post' | null; /** * @deprecated renamed to `order` */ enforce?: 'pre' | 'post'; /** * @deprecated renamed to `handler` */ transform: IndexHtmlTransformHook; } | { order?: 'pre' | 'post' | null; /** * @deprecated renamed to `order` */ enforce?: 'pre' | 'post'; handler: IndexHtmlTransformHook; };
type IndexHtmlTransformHook
type IndexHtmlTransformHook = ( this: void, html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
type IndexHtmlTransformResult
type IndexHtmlTransformResult = | string | HtmlTagDescriptor[] | { html: string; tags: HtmlTagDescriptor[]; };
type InferCustomEventPayload
type InferCustomEventPayload<T extends string> = T extends keyof CustomEventMap ? CustomEventMap[T] : any;
provides types for built-in Vite events
type LessPreprocessorOptions
type LessPreprocessorOptions = { additionalData?: PreprocessorAdditionalData;} & LessPreprocessorBaseOptions;
type LibraryFormats
type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system';
type LightningCSSOptions
type LightningCSSOptions = Omit< Lightningcss.BundleAsyncOptions<Lightningcss.CustomAtRules>, | 'filename' | 'resolver' | 'minify' | 'sourceMap' | 'analyzeDependencies' // properties not overridden by Vite, but does not make sense to set by end users | 'inputSourceMap' | 'projectRoot'>;
type LogLevel
type LogLevel = LogType | 'silent';
type LogType
type LogType = 'error' | 'warn' | 'info';
type Manifest
type Manifest = Record<string, ManifestChunk>;
type MapToFunction
type MapToFunction<T> = T extends Function ? T : never;
type Matcher
type AnymatchMatcher = AnymatchPattern | AnymatchPattern[];
type PluginOption
type PluginOption = Thenable<Plugin | FalsyPlugin | PluginOption[]>;
type PreviewServerHook
type PreviewServerHook = ( this: void, server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>;
type RenderBuiltAssetUrl
type RenderBuiltAssetUrl = ( filename: string, type: { type: 'asset' | 'public'; hostId: string; hostType: 'js' | 'css' | 'html'; ssr: boolean; }) => | string | { relative?: boolean; runtime?: string; } | undefined;
type ResolvedConfig
type ResolvedConfig = Readonly< Omit< UserConfig, | 'plugins' | 'css' | 'json' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build' | 'dev' | 'environments' | 'server' | 'preview' > & { configFile: string | undefined; 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[]; css: ResolvedCSSOptions; json: Required<JsonOptions>; esbuild: ESBuildOptions | false; server: ResolvedServerOptions; dev: ResolvedDevEnvironmentOptions; /** @experimental */ builder: ResolvedBuilderOptions | undefined; 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>; /** * The token to connect to the WebSocket server from browsers. * * We recommend using `import.meta.hot` rather than connecting * to the WebSocket server directly. * If you have a usecase that requires connecting to the WebSocket * server, please create an issue so that we can discuss. * * @deprecated */ webSocketToken: string; } & PluginHookUtils>;
type ResolvedCSSOptions
type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> & Required<Pick<CSSOptions, 'transformer'>> & { lightningcss?: LightningCSSOptions; };
type ResolvedDevEnvironmentOptions
type ResolvedDevEnvironmentOptions = Omit< Required<DevEnvironmentOptions>, 'sourcemapIgnoreList'> & { sourcemapIgnoreList: Exclude< DevEnvironmentOptions['sourcemapIgnoreList'], false | undefined >;};
type ResolvedUrl
type ResolvedUrl = [ url: string, resolvedId: string, meta: object | null | undefined];
type ResolveFn
type ResolveFn = ( id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
type ResolveModulePreloadDependenciesFn
type ResolveModulePreloadDependenciesFn = ( filename: string, deps: string[], context: { hostId: string; hostType: 'html' | 'js'; }) => string[];
type ResolverFunction
type ResolverFunction = MapToFunction<PluginHooks['resolveId']>;
type SassPreprocessorOptions
type SassPreprocessorOptions = { additionalData?: PreprocessorAdditionalData;} & ( | ({ api: 'legacy'; } & SassLegacyPreprocessBaseOptions) | ({ api?: 'modern' | 'modern-compiler'; } & SassModernPreprocessBaseOptions));
type ServerHMRChannel
type ServerHMRChannel = ServerHotChannel;
Deprecated
use
ServerHotChannel
instead
type ServerHook
type ServerHook = ( this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
type ServerHotChannel
type ServerHotChannel = HotChannel<ServerHotChannelApi>;
type SkipInformation
type SkipInformation = { id: string; importer: string | undefined; plugin: Plugin; called?: boolean;};
type SsrDepOptimizationConfig
type SsrDepOptimizationConfig = DepOptimizationConfig;
type SSRTarget
type SSRTarget = 'node' | 'webworker';
type StylusPreprocessorOptions
type StylusPreprocessorOptions = { additionalData?: PreprocessorAdditionalData;} & StylusPreprocessorBaseOptions;
type UserConfigExport
type UserConfigExport = | UserConfig | Promise<UserConfig> | UserConfigFnObject | UserConfigFnPromise | UserConfigFn;
type UserConfigFn
type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
type UserConfigFnObject
type UserConfigFnObject = (env: ConfigEnv) => UserConfig;
type UserConfigFnPromise
type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>;
type WebSocketCustomListener
type WebSocketCustomListener<T> = ( data: T, client: WebSocketClient, invoke?: 'send' | `send:${string}`) => void;
Namespaces
namespace *?no-inline
module '*?no-inline' {}
variable src
const src: string;
namespace *?sharedworker
module '*?sharedworker' {}
variable sharedWorkerConstructor
const sharedWorkerConstructor: new (options?: { name?: string }) => SharedWorker;
namespace *?sharedworker&inline
module '*?sharedworker&inline' {}
variable sharedWorkerConstructor
const sharedWorkerConstructor: new (options?: { name?: string }) => SharedWorker;
namespace *?sharedworker&url
module '*?sharedworker&url' {}
variable src
const src: string;
namespace *?url&inline
module '*?url&inline' {}
variable src
const src: string;
namespace *?worker
module '*?worker' {}
variable workerConstructor
const workerConstructor: new (options?: { name?: string }) => Worker;
namespace *?worker&inline
module '*?worker&inline' {}
variable workerConstructor
const workerConstructor: new (options?: { name?: string }) => Worker;
namespace *?worker&url
module '*?worker&url' {}
variable src
const src: string;
namespace *.css
module '*.css' {}
namespace *.less
module '*.less' {}
namespace *.module.css
module '*.module.css' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.less
module '*.module.less' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.pcss
module '*.module.pcss' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.sass
module '*.module.sass' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.scss
module '*.module.scss' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.sss
module '*.module.sss' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.styl
module '*.module.styl' {}
variable classes
const classes: CSSModuleClasses;
namespace *.module.stylus
module '*.module.stylus' {}
variable classes
const classes: CSSModuleClasses;
namespace *.pcss
module '*.pcss' {}
namespace *.sass
module '*.sass' {}
namespace *.scss
module '*.scss' {}
namespace *.sss
module '*.sss' {}
namespace *.styl
module '*.styl' {}
namespace *.stylus
module '*.stylus' {}
namespace *.wasm?init
module '*.wasm?init' {}
function initWasm
initWasm: (options?: WebAssembly.Imports) => Promise<WebAssembly.Instance>;
namespace *.webmanifest
module '*.webmanifest' {}
variable src
const src: string;
namespace Connect
namespace Connect {}
class IncomingMessage
class IncomingMessage extends http.IncomingMessage {}
property originalUrl
originalUrl?: any;
interface Server
interface Server extends NodeJS.EventEmitter {}
property route
route: string;
property stack
stack: ServerStackItem[];
method handle
handle: ( req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void;
Handle server requests, punting them down the middleware stack.
method listen
listen: { ( port: number, hostname?: string, backlog?: number, callback?: Function ): http.Server; (port: number, hostname?: string, callback?: Function): http.Server; (path: string, callback?: Function): http.Server; (handle: any, listeningListener?: Function): http.Server;};
Listen for connections.
This method takes the same arguments as node's
http.Server#listen()
.HTTP and HTTPS:
If you run your application both as HTTP and HTTPS you may wrap them individually, since your Connect "server" is really just a JavaScript
Function
.var connect = require('connect') , http = require('http') , https = require('https');
var app = connect();
http.createServer(app).listen(80); https.createServer(options, app).listen(443);
method use
use: { (fn: NextHandleFunction): Server; (fn: HandleFunction): Server; (route: string, fn: NextHandleFunction): Server; (route: string, fn: HandleFunction): Server;};
Utilize the given middleware
handle
to the givenroute
, defaulting to _/_. This "route" is the mount-point for the middleware, when given a value other than _/_ the middleware is only effective when that segment is present in the request's pathname.For example if we were to mount a function at _/admin_, it would be invoked on _/admin_, and _/admin/settings_, however it would not be invoked for _/_, or _/posts_.
call signature
(req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void;
interface ServerStackItem
interface ServerStackItem {}
type ErrorHandleFunction
type ErrorHandleFunction = ( err: any, req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
type HandleFunction
type HandleFunction = | SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction;
type NextFunction
type NextFunction = (err?: any) => void;
type NextHandleFunction
type NextHandleFunction = ( req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
type ServerHandle
type ServerHandle = HandleFunction | http.Server;
type SimpleHandleFunction
type SimpleHandleFunction = (req: IncomingMessage, res: http.ServerResponse) => void;
namespace HttpProxy
namespace HttpProxy {}
class Server
class Server extends events.EventEmitter {}
constructor
constructor(options?: ServerOptions);
Creates the proxy server with specified options.
Parameter options
Config object passed to the proxy
method addListener
addListener: (event: string, listener: () => void) => this;
method close
close: (callback?: () => void) => void;
A function that closes the inner webserver and stops listening on given port
method createProxy
static createProxy: (options?: ServerOptions) => Server;
Creates the proxy server with specified options.
Parameter options
Config object passed to the proxy
Returns
Proxy object with handlers for
ws
andweb
requests
method createProxyServer
static createProxyServer: (options?: ServerOptions) => Server;
Creates the proxy server with specified options.
Parameter options
Config object passed to the proxy
Returns
Proxy object with handlers for
ws
andweb
requests
method createServer
static createServer: (options?: ServerOptions) => Server;
Creates the proxy server with specified options.
Parameter options
Config object passed to the proxy
Returns
Proxy object with handlers for
ws
andweb
requests
method emit
emit: (event: string, ...args: any[]) => boolean;
method getMaxListeners
getMaxListeners: () => number;
method listen
listen: (port: number) => Server;
A function that wraps the object in a webserver, for your convenience
Parameter port
Port to listen on
method listenerCount
listenerCount: (type: string) => number;
method listeners
listeners: (event: string) => Array<() => void>;
method on
on: { (event: string, listener: () => void): this; (event: 'error', listener: ErrorCallback): this; ( event: 'start', listener: ( req: http.IncomingMessage, res: http.ServerResponse, target: any ) => void ): this; ( event: 'proxyReq', listener: ( proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse, options: ServerOptions ) => void ): this; ( event: 'proxyRes', listener: ( proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse ) => void ): this; ( event: 'proxyReqWs', listener: ( proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: net.Socket, options: ServerOptions, head: any ) => void ): this; ( event: 'econnreset', listener: ( err: Error, req: http.IncomingMessage, res: http.ServerResponse, target: any ) => void ): this; ( event: 'end', listener: ( req: http.IncomingMessage, res: http.ServerResponse, proxyRes: http.IncomingMessage ) => void ): this; ( event: 'close', listener: ( proxyRes: http.IncomingMessage, proxySocket: net.Socket, proxyHead: any ) => void ): this;};
method once
once: (event: string, listener: () => void) => this;
method removeAllListeners
removeAllListeners: (event?: string) => this;
method removeListener
removeListener: (event: string, listener: () => void) => this;
method setMaxListeners
setMaxListeners: (n: number) => this;
method web
web: ( req: http.IncomingMessage, res: http.ServerResponse, options?: ServerOptions, callback?: ErrorCallback) => void;
Used for proxying regular HTTP(S) requests
Parameter req
Client request.
Parameter res
Client response.
Parameter options
Additional options.
Parameter callback
Error callback.
method ws
ws: ( req: http.IncomingMessage, socket: unknown, head: unknown, options?: ServerOptions, callback?: ErrorCallback) => void;
Used for proxying regular HTTP(S) requests
Parameter req
Client request.
Parameter socket
Client socket.
Parameter head
Client head.
Parameter options
Additional options.
Parameter callback
Error callback.
interface ProxyTargetDetailed
interface ProxyTargetDetailed {}
property ca
ca?: string | undefined;
property cert
cert?: string | undefined;
property ciphers
ciphers?: string | undefined;
property host
host: string;
property hostname
hostname?: string | undefined;
property key
key?: string | undefined;
property passphrase
passphrase?: string | undefined;
property pfx
pfx?: Buffer | string | undefined;
property port
port: number;
property protocol
protocol?: string | undefined;
property secureProtocol
secureProtocol?: string | undefined;
property socketPath
socketPath?: string | undefined;
interface ServerOptions
interface ServerOptions {}
property agent
agent?: any;
Object to be passed to http(s).request.
property auth
auth?: string | undefined;
Basic authentication i.e. 'user:password' to compute an Authorization header.
property autoRewrite
autoRewrite?: boolean | undefined;
Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false.
property buffer
buffer?: stream.Stream | undefined;
Buffer
property changeOrigin
changeOrigin?: boolean | undefined;
Changes the origin of the host header to the target URL.
property cookieDomainRewrite
cookieDomainRewrite?: | false | string | { [oldDomain: string]: string } | undefined;
rewrites domain of set-cookie headers.
property cookiePathRewrite
cookiePathRewrite?: false | string | { [oldPath: string]: string } | undefined;
rewrites path of set-cookie headers. Default: false
property followRedirects
followRedirects?: boolean | undefined;
Specify whether you want to follow redirects. Default: false
property forward
forward?: ProxyTargetUrl | undefined;
URL string to be parsed with the url module.
property headers
headers?: { [header: string]: string } | undefined;
object with extra headers to be added to target requests.
property hostRewrite
hostRewrite?: string | undefined;
Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null.
property ignorePath
ignorePath?: boolean | undefined;
Specify whether you want to ignore the proxy path of the incoming request.
property localAddress
localAddress?: string | undefined;
Local interface string to bind for outgoing connections.
property prependPath
prependPath?: boolean | undefined;
Specify whether you want to prepend the target's path to the proxy path.
property preserveHeaderKeyCase
preserveHeaderKeyCase?: boolean | undefined;
specify whether you want to keep letter case of response header key
property protocolRewrite
protocolRewrite?: string | undefined;
Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null.
property proxyTimeout
proxyTimeout?: number | undefined;
Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes)
property secure
secure?: boolean | undefined;
Verify SSL certificate.
property selfHandleResponse
selfHandleResponse?: boolean | undefined;
If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event
property ssl
ssl?: any;
Object to be passed to https.createServer().
property target
target?: ProxyTarget | undefined;
URL string to be parsed with the url module.
property timeout
timeout?: number | undefined;
Timeout (in milliseconds) for incoming requests
property toProxy
toProxy?: boolean | undefined;
Explicitly specify if we are proxying to another proxy.
property ws
ws?: boolean | undefined;
If you want to proxy websockets.
property xfwd
xfwd?: boolean | undefined;
Adds x- forward headers.
type ErrorCallback
type ErrorCallback = ( err: Error, req: http.IncomingMessage, res: http.ServerResponse, target?: ProxyTargetUrl) => void;
type ProxyTarget
type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed;
type ProxyTargetUrl
type ProxyTargetUrl = string | Partial<url.Url>;
namespace Terser
namespace Terser {}
interface CompressOptions
interface CompressOptions {}
property arguments
arguments?: boolean;
property arrows
arrows?: boolean;
property booleans
booleans?: boolean;
property booleans_as_integers
booleans_as_integers?: boolean;
property collapse_vars
collapse_vars?: boolean;
property comparisons
comparisons?: boolean;
property computed_props
computed_props?: boolean;
property conditionals
conditionals?: boolean;
property dead_code
dead_code?: boolean;
property defaults
defaults?: boolean;
property directives
directives?: boolean;
property drop_console
drop_console?: DropConsoleOption;
property drop_debugger
drop_debugger?: boolean;
property ecma
ecma?: ECMA;
property evaluate
evaluate?: boolean;
property expression
expression?: boolean;
property global_defs
global_defs?: object;
property hoist_funs
hoist_funs?: boolean;
property hoist_props
hoist_props?: boolean;
property hoist_vars
hoist_vars?: boolean;
property ie8
ie8?: boolean;
property if_return
if_return?: boolean;
property inline
inline?: boolean | InlineFunctions;
property join_vars
join_vars?: boolean;
property keep_classnames
keep_classnames?: boolean | RegExp;
property keep_fargs
keep_fargs?: boolean;
property keep_fnames
keep_fnames?: boolean | RegExp;
property keep_infinity
keep_infinity?: boolean;
property loops
loops?: boolean;
property module
module?: boolean;
property negate_iife
negate_iife?: boolean;
property passes
passes?: number;
property properties
properties?: boolean;
property pure_funcs
pure_funcs?: string[];
property pure_getters
pure_getters?: boolean | 'strict';
property pure_new
pure_new?: boolean;
property reduce_funcs
reduce_funcs?: boolean;
property reduce_vars
reduce_vars?: boolean;
property sequences
sequences?: boolean | number;
property side_effects
side_effects?: boolean;
property switches
switches?: boolean;
property top_retain
top_retain?: null | string | string[] | RegExp;
property toplevel
toplevel?: boolean;
property typeofs
typeofs?: boolean;
property unsafe
unsafe?: boolean;
property unsafe_arrows
unsafe_arrows?: boolean;
property unsafe_comps
unsafe_comps?: boolean;
property unsafe_Function
unsafe_Function?: boolean;
property unsafe_math
unsafe_math?: boolean;
property unsafe_methods
unsafe_methods?: boolean;
property unsafe_proto
unsafe_proto?: boolean;
property unsafe_regexp
unsafe_regexp?: boolean;
property unsafe_symbols
unsafe_symbols?: boolean;
property unsafe_undefined
unsafe_undefined?: boolean;
property unused
unused?: boolean;
interface FormatOptions
interface FormatOptions {}
property ascii_only
ascii_only?: boolean;
property beautify
beautify?: boolean;
Deprecated
Not implemented anymore
property braces
braces?: boolean;
property comments
comments?: | boolean | 'all' | 'some' | RegExp | (( node: any, comment: { value: string; type: 'comment1' | 'comment2' | 'comment3' | 'comment4'; pos: number; line: number; col: number; } ) => boolean);
property ecma
ecma?: ECMA;
property ie8
ie8?: boolean;
property indent_level
indent_level?: number;
property indent_start
indent_start?: number;
property inline_script
inline_script?: boolean;
property keep_numbers
keep_numbers?: boolean;
property keep_quoted_props
keep_quoted_props?: boolean;
property max_line_len
max_line_len?: number | false;
property preamble
preamble?: string;
property preserve_annotations
preserve_annotations?: boolean;
property quote_keys
quote_keys?: boolean;
property quote_style
quote_style?: OutputQuoteStyle;
property safari10
safari10?: boolean;
property semicolons
semicolons?: boolean;
property shebang
shebang?: boolean;
property shorthand
shorthand?: boolean;
property source_map
source_map?: SourceMapOptions;
property webkit
webkit?: boolean;
property width
width?: number;
property wrap_func_args
wrap_func_args?: boolean;
property wrap_iife
wrap_iife?: boolean;
interface MangleOptions
interface MangleOptions {}
property eval
eval?: boolean;
property keep_classnames
keep_classnames?: boolean | RegExp;
property keep_fnames
keep_fnames?: boolean | RegExp;
property module
module?: boolean;
property nth_identifier
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
property properties
properties?: boolean | ManglePropertiesOptions;
property reserved
reserved?: string[];
property safari10
safari10?: boolean;
property toplevel
toplevel?: boolean;
interface ManglePropertiesOptions
interface ManglePropertiesOptions {}
property builtins
builtins?: boolean;
property debug
debug?: boolean;
property keep_quoted
keep_quoted?: boolean | 'strict';
property nth_identifier
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
property regex
regex?: RegExp | string;
property reserved
reserved?: string[];
interface MinifyOptions
interface MinifyOptions {}
property compress
compress?: boolean | CompressOptions;
property ecma
ecma?: ECMA;
property enclose
enclose?: boolean | string;
property format
format?: FormatOptions;
property ie8
ie8?: boolean;
property keep_classnames
keep_classnames?: boolean | RegExp;
property keep_fnames
keep_fnames?: boolean | RegExp;
property mangle
mangle?: boolean | MangleOptions;
property module
module?: boolean;
property nameCache
nameCache?: object;
property output
output?: FormatOptions;
Deprecated
property parse
parse?: ParseOptions;
property safari10
safari10?: boolean;
property sourceMap
sourceMap?: boolean | SourceMapOptions;
property toplevel
toplevel?: boolean;
interface MinifyOutput
interface MinifyOutput {}
property code
code?: string;
property decoded_map
decoded_map?: object | null;
property map
map?: object | string;
interface ParseOptions
interface ParseOptions {}
property bare_returns
bare_returns?: boolean;
property ecma
ecma?: ECMA;
Deprecated
legacy option. Currently, all supported EcmaScript is valid to parse.
property html5_comments
html5_comments?: boolean;
property shebang
shebang?: boolean;
interface SimpleIdentifierMangler
interface SimpleIdentifierMangler {}
An identifier mangler for which the output is invariant with respect to the source code.
method get
get: (n: number) => string;
Obtains the nth most favored (usually shortest) identifier to rename a variable to. The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word. This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
Parameter n
The ordinal of the identifier.
interface SourceMapOptions
interface SourceMapOptions {}
interface WeightedIdentifierMangler
interface WeightedIdentifierMangler extends SimpleIdentifierMangler {}
An identifier mangler that leverages character frequency analysis to determine identifier precedence.
method consider
consider: (chars: string, delta: number) => number;
Modifies the internal weighting of the input characters by the specified delta. Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
Parameter chars
The characters to modify the weighting of.
Parameter delta
The numeric weight to add to the characters.
method reset
reset: () => void;
Resets character weights.
method sort
sort: () => void;
Sorts identifiers by character frequency, in preparation for calls to get(n).
enum InlineFunctions
enum InlineFunctions { Disabled = 0, SimpleFunctions = 1, WithArguments = 2, WithArgumentsAndVariables = 3,}
member Disabled
Disabled = 0
member SimpleFunctions
SimpleFunctions = 1
member WithArguments
WithArguments = 2
member WithArgumentsAndVariables
WithArgumentsAndVariables = 3
enum OutputQuoteStyle
enum OutputQuoteStyle { PreferDouble = 0, AlwaysSingle = 1, AlwaysDouble = 2, AlwaysOriginal = 3,}
member AlwaysDouble
AlwaysDouble = 2
member AlwaysOriginal
AlwaysOriginal = 3
member AlwaysSingle
AlwaysSingle = 1
member PreferDouble
PreferDouble = 0
type ConsoleProperty
type ConsoleProperty = keyof typeof console;
type DropConsoleOption
type DropConsoleOption = boolean | ConsoleProperty[];
type ECMA
type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020;
namespace WebSocket
namespace WebSocket {}
variable WebSocket
const WebSocket: typeof WebSocket;
variable WebSocketServer
const WebSocketServer: typeof Server;
function createWebSocketStream
createWebSocketStream: (websocket: WebSocket, options?: DuplexOptions) => Duplex;
class Server
class Server<T extends WebSocket = WebSocket> extends EventEmitter {}
constructor
constructor(options?: ServerOptions, callback?: () => void);
property clients
clients: Set<T>;
property options
options: ServerOptions;
property path
path: string;
method addListener
addListener: { ( event: 'connection', cb: (client: T, request: IncomingMessage) => void ): this; (event: 'error', cb: (err: Error) => void): this; ( event: 'headers', cb: (headers: string[], request: IncomingMessage) => void ): this; (event: 'close' | 'listening', cb: () => void): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
method address
address: () => AddressInfo | string;
method close
close: (cb?: (err?: Error) => void) => void;
method handleUpgrade
handleUpgrade: ( request: IncomingMessage, socket: Duplex, upgradeHead: Buffer, callback: (client: T, request: IncomingMessage) => void) => void;
method off
off: { ( event: 'connection', cb: (this: Server<T>, socket: T, request: IncomingMessage) => void ): this; (event: 'error', cb: (this: Server<T>, error: Error) => void): this; ( event: 'headers', cb: ( this: Server<T>, headers: string[], request: IncomingMessage ) => void ): this; (event: 'close' | 'listening', cb: (this: Server<T>) => void): this; ( event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void ): this;};
method on
on: { ( event: 'connection', cb: (this: Server<T>, socket: T, request: IncomingMessage) => void ): this; (event: 'error', cb: (this: Server<T>, error: Error) => void): this; ( event: 'headers', cb: ( this: Server<T>, headers: string[], request: IncomingMessage ) => void ): this; (event: 'close' | 'listening', cb: (this: Server<T>) => void): this; ( event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void ): this;};
method once
once: { ( event: 'connection', cb: (this: Server<T>, socket: T, request: IncomingMessage) => void ): this; (event: 'error', cb: (this: Server<T>, error: Error) => void): this; ( event: 'headers', cb: ( this: Server<T>, headers: string[], request: IncomingMessage ) => void ): this; (event: 'close' | 'listening', cb: (this: Server<T>) => void): this; ( event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void ): this;};
method removeListener
removeListener: { (event: 'connection', cb: (client: T) => void): this; (event: 'error', cb: (err: Error) => void): this; ( event: 'headers', cb: (headers: string[], request: IncomingMessage) => void ): this; (event: 'close' | 'listening', cb: () => void): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
method shouldHandle
shouldHandle: (request: IncomingMessage) => boolean | Promise<boolean>;
interface AddressInfo
interface AddressInfo {}
interface ClientOptions
interface ClientOptions extends SecureContextOptions {}
property agent
agent?: Agent | undefined;
property family
family?: number | undefined;
property followRedirects
followRedirects?: boolean | undefined;
property handshakeTimeout
handshakeTimeout?: number | undefined;
property headers
headers?: { [key: string]: string } | undefined;
property host
host?: string | undefined;
property localAddress
localAddress?: string | undefined;
property maxPayload
maxPayload?: number | undefined;
property maxRedirects
maxRedirects?: number | undefined;
property origin
origin?: string | undefined;
property perMessageDeflate
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
property protocol
protocol?: string | undefined;
property protocolVersion
protocolVersion?: number | undefined;
property rejectUnauthorized
rejectUnauthorized?: boolean | undefined;
property skipUTF8Validation
skipUTF8Validation?: boolean | undefined;
method checkServerIdentity
checkServerIdentity: (servername: string, cert: CertMeta) => boolean;
method generateMask
generateMask: (mask: Buffer) => void;
interface CloseEvent
interface CloseEvent {}
interface ErrorEvent
interface ErrorEvent {}
interface EventListenerOptions
interface EventListenerOptions {}
property once
once?: boolean | undefined;
interface MessageEvent
interface MessageEvent {}
interface PerMessageDeflateOptions
interface PerMessageDeflateOptions {}
property clientMaxWindowBits
clientMaxWindowBits?: number | undefined;
property clientNoContextTakeover
clientNoContextTakeover?: boolean | undefined;
property concurrencyLimit
concurrencyLimit?: number | undefined;
property serverMaxWindowBits
serverMaxWindowBits?: number | undefined;
property serverNoContextTakeover
serverNoContextTakeover?: boolean | undefined;
property threshold
threshold?: number | undefined;
property zlibDeflateOptions
zlibDeflateOptions?: | { flush?: number | undefined; finishFlush?: number | undefined; chunkSize?: number | undefined; windowBits?: number | undefined; level?: number | undefined; memLevel?: number | undefined; strategy?: number | undefined; dictionary?: Buffer | Buffer[] | DataView | undefined; info?: boolean | undefined; } | undefined;
property zlibInflateOptions
zlibInflateOptions?: ZlibOptions | undefined;
interface ServerOptions
interface ServerOptions {}
property backlog
backlog?: number | undefined;
property clientTracking
clientTracking?: boolean | undefined;
property handleProtocols
handleProtocols?: ( protocols: Set<string>, request: IncomingMessage) => string | false;
property host
host?: string | undefined;
property maxPayload
maxPayload?: number | undefined;
property noServer
noServer?: boolean | undefined;
property path
path?: string | undefined;
property perMessageDeflate
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
property port
port?: number | undefined;
property server
server?: Server | HttpsServer | undefined;
property skipUTF8Validation
skipUTF8Validation?: boolean | undefined;
property verifyClient
verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync | undefined;
property WebSocket
WebSocket?: typeof WebSocket.WebSocket | undefined;
interface WebSocket
interface WebSocket extends WebSocketAlias {}
interface WebSocketServer
interface WebSocketServer extends Server {}
type CertMeta
type CertMeta = string | string[] | Buffer | Buffer[];
CertMeta represents the accepted types for certificate & key data.
type Data
type Data = string | Buffer | ArrayBuffer | Buffer[];
Data represents the message payload received over the WebSocket.
type RawData
type RawData = Buffer | ArrayBuffer | Buffer[];
Data represents the raw message payload received over the WebSocket.
type VerifyClientCallbackAsync
type VerifyClientCallbackAsync = ( info: { origin: string; secure: boolean; req: IncomingMessage }, callback: ( res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders ) => void) => void;
VerifyClientCallbackAsync is an asynchronous callback used to inspect the incoming message. The return value (boolean) of the function determines whether or not to accept the handshake.
type VerifyClientCallbackSync
type VerifyClientCallbackSync = (info: { origin: string; secure: boolean; req: IncomingMessage;}) => boolean;
VerifyClientCallbackSync is a synchronous callback used to inspect the incoming message. The return value (boolean) of the function determines whether or not to accept the handshake.
Package Files (7)
Dependencies (3)
Dev Dependencies (59)
- @ampproject/remapping
- @babel/parser
- @jridgewell/trace-mapping
- @polka/compression
- @rollup/plugin-alias
- @rollup/plugin-commonjs
- @rollup/plugin-dynamic-import-vars
- @rollup/plugin-json
- @rollup/plugin-node-resolve
- @rollup/pluginutils
- @types/escape-html
- @types/pnpapi
- artichokie
- cac
- chokidar
- connect
- convert-source-map
- cors
- cross-spawn
- debug
- dep-types
- dotenv
- dotenv-expand
- es-module-lexer
- escape-html
- estree-walker
- etag
- http-proxy
- launch-editor-middleware
- lightningcss
- magic-string
- mlly
- mrmime
- nanoid
- open
- parse5
- pathe
- periscopic
- picocolors
- picomatch
- postcss-import
- postcss-load-config
- postcss-modules
- resolve.exports
- rollup-plugin-dts
- rollup-plugin-esbuild
- rollup-plugin-license
- sass
- sass-embedded
- sirv
- source-map-support
- strip-literal
- terser
- tinyglobby
- tsconfck
- tslib
- types
- ufo
- ws
Peer Dependencies (11)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/vite
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/vite)
- HTML<a href="https://www.jsdocs.io/package/vite"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 13854 ms. - Missing or incorrect documentation? Open an issue for this package.