UNPKG

149 kBTypeScriptView Raw
1/// <reference types="node" />
2import { PluginHooks, RollupError, SourceMap, ModuleInfo, PartialResolvedId, RollupOptions, WatcherOptions, InputOption, ModuleFormat, RollupOutput, RollupWatcher, MinimalPluginContext, InputOptions, CustomPluginOptions, LoadResult, SourceDescription, SourceMapInput, ExistingRawSourceMap, OutputBundle, OutputChunk, ObjectHook, ResolveIdResult, GetManualChunk } from 'rollup';
3import * as rollup from 'rollup';
4export { rollup as Rollup };
5export { parseAst, parseAstAsync } from 'rollup/parseAst';
6import * as http from 'node:http';
7import { OutgoingHttpHeaders, ClientRequestArgs, IncomingMessage, ClientRequest, Agent, Server, ServerResponse } from 'node:http';
8import { Http2SecureServer } from 'node:http2';
9import * as fs from 'node:fs';
10import * as events from 'node:events';
11import { EventEmitter } from 'node:events';
12import { ServerOptions as HttpsServerOptions, Server as HttpsServer } from 'node:https';
13import * as net from 'node:net';
14import * as url from 'node:url';
15import { URL } from 'node:url';
16import * as stream from 'node:stream';
17import { Duplex, DuplexOptions } from 'node:stream';
18import { FetchFunctionOptions, FetchResult, ModuleRunnerOptions, ModuleRunnerHmr, ModuleEvaluator, ModuleRunner } from 'vite/module-runner';
19export { FetchFunction, FetchResult } from 'vite/module-runner';
20import { BuildOptions as esbuild_BuildOptions, TransformOptions as esbuild_TransformOptions, TransformResult as esbuild_TransformResult } from 'esbuild';
21export { TransformOptions as EsbuildTransformOptions, version as esbuildVersion } from 'esbuild';
22import { HotPayload, CustomPayload } from '../../types/hmrPayload.js';
23export { ConnectedPayload, CustomPayload, ErrorPayload, FullReloadPayload, HMRPayload, HotPayload, PrunePayload, Update, UpdatePayload } from '../../types/hmrPayload.js';
24import { InferCustomEventPayload } from '../../types/customEvent.js';
25export { CustomEventMap, InferCustomEventPayload, InvalidatePayload } from '../../types/customEvent.js';
26import { SecureContextOptions } from 'node:tls';
27import { ZlibOptions } from 'node:zlib';
28import * as PostCSS from 'postcss';
29import { LightningCSSOptions } from '../../types/internal/lightningcssOptions.js';
30export { LightningCSSOptions } from '../../types/internal/lightningcssOptions.js';
31import { SassLegacyPreprocessBaseOptions, SassModernPreprocessBaseOptions, LessPreprocessorBaseOptions, StylusPreprocessorBaseOptions } from '../../types/internal/cssPreprocessorOptions.js';
32export { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from '../../types/importGlob.js';
33export { ChunkMetadata } from '../../types/metadata.js';
34
35interface Alias {
36 find: string | RegExp
37 replacement: string
38 /**
39 * Instructs the plugin to use an alternative resolving algorithm,
40 * rather than the Rollup's resolver.
41 * @default null
42 */
43 customResolver?: ResolverFunction | ResolverObject | null
44}
45
46type MapToFunction<T> = T extends Function ? T : never
47
48type ResolverFunction = MapToFunction<PluginHooks['resolveId']>
49
50interface ResolverObject {
51 buildStart?: PluginHooks['buildStart']
52 resolveId: ResolverFunction
53}
54
55/**
56 * Specifies an `Object`, or an `Array` of `Object`,
57 * which defines aliases used to replace values in `import` or `require` statements.
58 * With either format, the order of the entries is important,
59 * in that the first defined rules are applied first.
60 *
61 * This is passed to \@rollup/plugin-alias as the "entries" field
62 * https://github.com/rollup/plugins/tree/master/packages/alias#entries
63 */
64type AliasOptions = readonly Alias[] | { [find: string]: string }
65
66type AnymatchFn = (testString: string) => boolean
67type AnymatchPattern = string | RegExp | AnymatchFn
68type AnymatchMatcher = AnymatchPattern | AnymatchPattern[]
69
70// Inlined to avoid extra dependency (chokidar is bundled in the published build)
71
72declare class FSWatcher extends EventEmitter implements fs.FSWatcher {
73 options: WatchOptions
74
75 /**
76 * Constructs a new FSWatcher instance with optional WatchOptions parameter.
77 */
78 constructor(options?: WatchOptions)
79
80 /**
81 * When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active.
82 * Calling watcher.ref() multiple times will have no effect.
83 */
84 ref(): this
85
86 /**
87 * When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active.
88 * If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked.
89 * Calling watcher.unref() multiple times will have no effect.
90 */
91 unref(): this
92
93 /**
94 * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
95 * string.
96 */
97 add(paths: string | ReadonlyArray<string>): this
98
99 /**
100 * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
101 * string.
102 */
103 unwatch(paths: string | ReadonlyArray<string>): this
104
105 /**
106 * Returns an object representing all the paths on the file system being watched by this
107 * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
108 * the `cwd` option was used), and the values are arrays of the names of the items contained in
109 * each directory.
110 */
111 getWatched(): {
112 [directory: string]: string[]
113 }
114
115 /**
116 * Removes all listeners from watched files.
117 */
118 close(): Promise<void>
119
120 on(
121 event: 'add' | 'addDir' | 'change',
122 listener: (path: string, stats?: fs.Stats) => void,
123 ): this
124
125 on(
126 event: 'all',
127 listener: (
128 eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
129 path: string,
130 stats?: fs.Stats,
131 ) => void,
132 ): this
133
134 /**
135 * Error occurred
136 */
137 on(event: 'error', listener: (error: Error) => void): this
138
139 /**
140 * Exposes the native Node `fs.FSWatcher events`
141 */
142 on(
143 event: 'raw',
144 listener: (eventName: string, path: string, details: any) => void,
145 ): this
146
147 /**
148 * Fires when the initial scan is complete
149 */
150 on(event: 'ready', listener: () => void): this
151
152 on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this
153
154 on(event: string, listener: (...args: any[]) => void): this
155}
156
157interface WatchOptions {
158 /**
159 * Indicates whether the process should continue to run as long as files are being watched. If
160 * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
161 * even if the process continues to run.
162 */
163 persistent?: boolean
164
165 /**
166 * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
167 * be ignored. The whole relative or absolute path is tested, not just filename. If a function
168 * with two arguments is provided, it gets called twice per path - once with a single argument
169 * (the path), second time with two arguments (the path and the
170 * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
171 */
172 ignored?: AnymatchMatcher
173
174 /**
175 * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
176 * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
177 */
178 ignoreInitial?: boolean
179
180 /**
181 * When `false`, only the symlinks themselves will be watched for changes instead of following
182 * the link references and bubbling events through the link's path.
183 */
184 followSymlinks?: boolean
185
186 /**
187 * The base directory from which watch `paths` are to be derived. Paths emitted with events will
188 * be relative to this.
189 */
190 cwd?: string
191
192 /**
193 * If set to true then the strings passed to .watch() and .add() are treated as literal path
194 * names, even if they look like globs.
195 *
196 * @default false
197 */
198 disableGlobbing?: boolean
199
200 /**
201 * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
202 * utilization, consider setting this to `false`. It is typically necessary to **set this to
203 * `true` to successfully watch files over a network**, and it may be necessary to successfully
204 * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
205 * the `useFsEvents` default.
206 */
207 usePolling?: boolean
208
209 /**
210 * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
211 * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on
212 * OS X, `usePolling: true` becomes the default.
213 */
214 useFsEvents?: boolean
215
216 /**
217 * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
218 * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
219 * provided even in cases where it wasn't already available from the underlying watch events.
220 */
221 alwaysStat?: boolean
222
223 /**
224 * If set, limits how many levels of subdirectories will be traversed.
225 */
226 depth?: number
227
228 /**
229 * Interval of file system polling.
230 */
231 interval?: number
232
233 /**
234 * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
235 * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
236 */
237 binaryInterval?: number
238
239 /**
240 * Indicates whether to watch files that don't have read permissions if possible. If watching
241 * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
242 * silently.
243 */
244 ignorePermissionErrors?: boolean
245
246 /**
247 * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts
248 * that occur when using editors that use "atomic writes" instead of writing directly to the
249 * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
250 * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
251 * you can override it by setting `atomic` to a custom value, in milliseconds.
252 */
253 atomic?: boolean | number
254
255 /**
256 * can be set to an object in order to adjust timing params:
257 */
258 awaitWriteFinish?: AwaitWriteFinishOptions | boolean
259}
260
261interface AwaitWriteFinishOptions {
262 /**
263 * Amount of time in milliseconds for a file size to remain constant before emitting its event.
264 */
265 stabilityThreshold?: number
266
267 /**
268 * File size polling interval.
269 */
270 pollInterval?: number
271}
272
273// Inlined to avoid extra dependency
274// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
275
276declare namespace Connect {
277 export type ServerHandle = HandleFunction | http.Server
278
279 export class IncomingMessage extends http.IncomingMessage {
280 originalUrl?: http.IncomingMessage['url'] | undefined
281 }
282
283 export type NextFunction = (err?: any) => void
284
285 export type SimpleHandleFunction = (
286 req: IncomingMessage,
287 res: http.ServerResponse,
288 ) => void
289 export type NextHandleFunction = (
290 req: IncomingMessage,
291 res: http.ServerResponse,
292 next: NextFunction,
293 ) => void
294 export type ErrorHandleFunction = (
295 err: any,
296 req: IncomingMessage,
297 res: http.ServerResponse,
298 next: NextFunction,
299 ) => void
300 export type HandleFunction =
301 | SimpleHandleFunction
302 | NextHandleFunction
303 | ErrorHandleFunction
304
305 export interface ServerStackItem {
306 route: string
307 handle: ServerHandle
308 }
309
310 export interface Server extends NodeJS.EventEmitter {
311 (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void
312
313 route: string
314 stack: ServerStackItem[]
315
316 /**
317 * Utilize the given middleware `handle` to the given `route`,
318 * defaulting to _/_. This "route" is the mount-point for the
319 * middleware, when given a value other than _/_ the middleware
320 * is only effective when that segment is present in the request's
321 * pathname.
322 *
323 * For example if we were to mount a function at _/admin_, it would
324 * be invoked on _/admin_, and _/admin/settings_, however it would
325 * not be invoked for _/_, or _/posts_.
326 */
327 use(fn: NextHandleFunction): Server
328 use(fn: HandleFunction): Server
329 use(route: string, fn: NextHandleFunction): Server
330 use(route: string, fn: HandleFunction): Server
331
332 /**
333 * Handle server requests, punting them down
334 * the middleware stack.
335 */
336 handle(
337 req: http.IncomingMessage,
338 res: http.ServerResponse,
339 next: Function,
340 ): void
341
342 /**
343 * Listen for connections.
344 *
345 * This method takes the same arguments
346 * as node's `http.Server#listen()`.
347 *
348 * HTTP and HTTPS:
349 *
350 * If you run your application both as HTTP
351 * and HTTPS you may wrap them individually,
352 * since your Connect "server" is really just
353 * a JavaScript `Function`.
354 *
355 * var connect = require('connect')
356 * , http = require('http')
357 * , https = require('https');
358 *
359 * var app = connect();
360 *
361 * http.createServer(app).listen(80);
362 * https.createServer(options, app).listen(443);
363 */
364 listen(
365 port: number,
366 hostname?: string,
367 backlog?: number,
368 callback?: Function,
369 ): http.Server
370 listen(port: number, hostname?: string, callback?: Function): http.Server
371 listen(path: string, callback?: Function): http.Server
372 listen(handle: any, listeningListener?: Function): http.Server
373 }
374}
375
376// Inlined to avoid extra dependency
377// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
378
379declare namespace HttpProxy {
380 export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed
381
382 export type ProxyTargetUrl = string | Partial<url.Url>
383
384 export interface ProxyTargetDetailed {
385 host: string
386 port: number
387 protocol?: string | undefined
388 hostname?: string | undefined
389 socketPath?: string | undefined
390 key?: string | undefined
391 passphrase?: string | undefined
392 pfx?: Buffer | string | undefined
393 cert?: string | undefined
394 ca?: string | undefined
395 ciphers?: string | undefined
396 secureProtocol?: string | undefined
397 }
398
399 export type ErrorCallback = (
400 err: Error,
401 req: http.IncomingMessage,
402 res: http.ServerResponse,
403 target?: ProxyTargetUrl,
404 ) => void
405
406 export class Server extends events.EventEmitter {
407 /**
408 * Creates the proxy server with specified options.
409 * @param options - Config object passed to the proxy
410 */
411 constructor(options?: ServerOptions)
412
413 /**
414 * Used for proxying regular HTTP(S) requests
415 * @param req - Client request.
416 * @param res - Client response.
417 * @param options - Additional options.
418 * @param callback - Error callback.
419 */
420 web(
421 req: http.IncomingMessage,
422 res: http.ServerResponse,
423 options?: ServerOptions,
424 callback?: ErrorCallback,
425 ): void
426
427 /**
428 * Used for proxying regular HTTP(S) requests
429 * @param req - Client request.
430 * @param socket - Client socket.
431 * @param head - Client head.
432 * @param options - Additional options.
433 * @param callback - Error callback.
434 */
435 ws(
436 req: http.IncomingMessage,
437 socket: unknown,
438 head: unknown,
439 options?: ServerOptions,
440 callback?: ErrorCallback,
441 ): void
442
443 /**
444 * A function that wraps the object in a webserver, for your convenience
445 * @param port - Port to listen on
446 */
447 listen(port: number): Server
448
449 /**
450 * A function that closes the inner webserver and stops listening on given port
451 */
452 close(callback?: () => void): void
453
454 /**
455 * Creates the proxy server with specified options.
456 * @param options - Config object passed to the proxy
457 * @returns Proxy object with handlers for `ws` and `web` requests
458 */
459 static createProxyServer(options?: ServerOptions): Server
460
461 /**
462 * Creates the proxy server with specified options.
463 * @param options - Config object passed to the proxy
464 * @returns Proxy object with handlers for `ws` and `web` requests
465 */
466 static createServer(options?: ServerOptions): Server
467
468 /**
469 * Creates the proxy server with specified options.
470 * @param options - Config object passed to the proxy
471 * @returns Proxy object with handlers for `ws` and `web` requests
472 */
473 static createProxy(options?: ServerOptions): Server
474
475 addListener(event: string, listener: () => void): this
476 on(event: string, listener: () => void): this
477 on(event: 'error', listener: ErrorCallback): this
478 on(
479 event: 'start',
480 listener: (
481 req: http.IncomingMessage,
482 res: http.ServerResponse,
483 target: ProxyTargetUrl,
484 ) => void,
485 ): this
486 on(
487 event: 'proxyReq',
488 listener: (
489 proxyReq: http.ClientRequest,
490 req: http.IncomingMessage,
491 res: http.ServerResponse,
492 options: ServerOptions,
493 ) => void,
494 ): this
495 on(
496 event: 'proxyRes',
497 listener: (
498 proxyRes: http.IncomingMessage,
499 req: http.IncomingMessage,
500 res: http.ServerResponse,
501 ) => void,
502 ): this
503 on(
504 event: 'proxyReqWs',
505 listener: (
506 proxyReq: http.ClientRequest,
507 req: http.IncomingMessage,
508 socket: net.Socket,
509 options: ServerOptions,
510 head: any,
511 ) => void,
512 ): this
513 on(
514 event: 'econnreset',
515 listener: (
516 err: Error,
517 req: http.IncomingMessage,
518 res: http.ServerResponse,
519 target: ProxyTargetUrl,
520 ) => void,
521 ): this
522 on(
523 event: 'end',
524 listener: (
525 req: http.IncomingMessage,
526 res: http.ServerResponse,
527 proxyRes: http.IncomingMessage,
528 ) => void,
529 ): this
530 on(
531 event: 'close',
532 listener: (
533 proxyRes: http.IncomingMessage,
534 proxySocket: net.Socket,
535 proxyHead: any,
536 ) => void,
537 ): this
538
539 once(event: string, listener: () => void): this
540 removeListener(event: string, listener: () => void): this
541 removeAllListeners(event?: string): this
542 getMaxListeners(): number
543 setMaxListeners(n: number): this
544 listeners(event: string): Array<() => void>
545 emit(event: string, ...args: any[]): boolean
546 listenerCount(type: string): number
547 }
548
549 export interface ServerOptions {
550 /** URL string to be parsed with the url module. */
551 target?: ProxyTarget | undefined
552 /** URL string to be parsed with the url module. */
553 forward?: ProxyTargetUrl | undefined
554 /** Object to be passed to http(s).request. */
555 agent?: any
556 /** Object to be passed to https.createServer(). */
557 ssl?: any
558 /** If you want to proxy websockets. */
559 ws?: boolean | undefined
560 /** Adds x- forward headers. */
561 xfwd?: boolean | undefined
562 /** Verify SSL certificate. */
563 secure?: boolean | undefined
564 /** Explicitly specify if we are proxying to another proxy. */
565 toProxy?: boolean | undefined
566 /** Specify whether you want to prepend the target's path to the proxy path. */
567 prependPath?: boolean | undefined
568 /** Specify whether you want to ignore the proxy path of the incoming request. */
569 ignorePath?: boolean | undefined
570 /** Local interface string to bind for outgoing connections. */
571 localAddress?: string | undefined
572 /** Changes the origin of the host header to the target URL. */
573 changeOrigin?: boolean | undefined
574 /** specify whether you want to keep letter case of response header key */
575 preserveHeaderKeyCase?: boolean | undefined
576 /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
577 auth?: string | undefined
578 /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
579 hostRewrite?: string | undefined
580 /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
581 autoRewrite?: boolean | undefined
582 /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
583 protocolRewrite?: string | undefined
584 /** rewrites domain of set-cookie headers. */
585 cookieDomainRewrite?:
586 | false
587 | string
588 | { [oldDomain: string]: string }
589 | undefined
590 /** rewrites path of set-cookie headers. Default: false */
591 cookiePathRewrite?:
592 | false
593 | string
594 | { [oldPath: string]: string }
595 | undefined
596 /** object with extra headers to be added to target requests. */
597 headers?: { [header: string]: string } | undefined
598 /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
599 proxyTimeout?: number | undefined
600 /** Timeout (in milliseconds) for incoming requests */
601 timeout?: number | undefined
602 /** Specify whether you want to follow redirects. Default: false */
603 followRedirects?: boolean | undefined
604 /** 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 */
605 selfHandleResponse?: boolean | undefined
606 /** Buffer */
607 buffer?: stream.Stream | undefined
608 }
609}
610
611interface ProxyOptions extends HttpProxy.ServerOptions {
612 /**
613 * rewrite path
614 */
615 rewrite?: (path: string) => string;
616 /**
617 * configure the proxy server (e.g. listen to events)
618 */
619 configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
620 /**
621 * webpack-dev-server style bypass function
622 */
623 bypass?: (req: http.IncomingMessage,
624 /** undefined for WebSocket upgrade requests */
625 res: http.ServerResponse | undefined, options: ProxyOptions) => void | null | undefined | false | string;
626 /**
627 * rewrite the Origin header of a WebSocket request to match the target
628 *
629 * **Exercise caution as rewriting the Origin can leave the proxying open to [CSRF attacks](https://owasp.org/www-community/attacks/csrf).**
630 */
631 rewriteWsOrigin?: boolean | undefined;
632}
633
634type LogType = 'error' | 'warn' | 'info';
635type LogLevel = LogType | 'silent';
636interface Logger {
637 info(msg: string, options?: LogOptions): void;
638 warn(msg: string, options?: LogOptions): void;
639 warnOnce(msg: string, options?: LogOptions): void;
640 error(msg: string, options?: LogErrorOptions): void;
641 clearScreen(type: LogType): void;
642 hasErrorLogged(error: Error | RollupError): boolean;
643 hasWarned: boolean;
644}
645interface LogOptions {
646 clear?: boolean;
647 timestamp?: boolean;
648 environment?: string;
649}
650interface LogErrorOptions extends LogOptions {
651 error?: Error | RollupError | null;
652}
653interface LoggerOptions {
654 prefix?: string;
655 allowClearScreen?: boolean;
656 customLogger?: Logger;
657 console?: Console;
658}
659declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
660
661interface CommonServerOptions {
662 /**
663 * Specify server port. Note if the port is already being used, Vite will
664 * automatically try the next available port so this may not be the actual
665 * port the server ends up listening on.
666 */
667 port?: number;
668 /**
669 * If enabled, vite will exit if specified port is already in use
670 */
671 strictPort?: boolean;
672 /**
673 * Specify which IP addresses the server should listen on.
674 * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
675 */
676 host?: string | boolean;
677 /**
678 * Enable TLS + HTTP/2.
679 * Note: this downgrades to TLS only when the proxy option is also used.
680 */
681 https?: HttpsServerOptions;
682 /**
683 * Open browser window on startup
684 */
685 open?: boolean | string;
686 /**
687 * Configure custom proxy rules for the dev server. Expects an object
688 * of `{ key: options }` pairs.
689 * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
690 * Full options [here](https://github.com/http-party/node-http-proxy#options).
691 *
692 * Example `vite.config.js`:
693 * ``` js
694 * module.exports = {
695 * proxy: {
696 * // string shorthand: /foo -> http://localhost:4567/foo
697 * '/foo': 'http://localhost:4567',
698 * // with options
699 * '/api': {
700 * target: 'http://jsonplaceholder.typicode.com',
701 * changeOrigin: true,
702 * rewrite: path => path.replace(/^\/api/, '')
703 * }
704 * }
705 * }
706 * ```
707 */
708 proxy?: Record<string, string | ProxyOptions>;
709 /**
710 * Configure CORS for the dev server.
711 * Uses https://github.com/expressjs/cors.
712 * Set to `true` to allow all methods from any origin, or configure separately
713 * using an object.
714 */
715 cors?: CorsOptions | boolean;
716 /**
717 * Specify server response headers.
718 */
719 headers?: OutgoingHttpHeaders;
720}
721/**
722 * https://github.com/expressjs/cors#configuration-options
723 */
724interface CorsOptions {
725 origin?: CorsOrigin | ((origin: string | undefined, cb: (err: Error, origins: CorsOrigin) => void) => void);
726 methods?: string | string[];
727 allowedHeaders?: string | string[];
728 exposedHeaders?: string | string[];
729 credentials?: boolean;
730 maxAge?: number;
731 preflightContinue?: boolean;
732 optionsSuccessStatus?: number;
733}
734type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
735
736type RequiredExceptFor<T, K extends keyof T> = Pick<T, K> & Required<Omit<T, K>>;
737
738interface PreviewOptions extends CommonServerOptions {
739}
740interface ResolvedPreviewOptions extends RequiredExceptFor<PreviewOptions, 'host' | 'https' | 'proxy'> {
741}
742interface PreviewServer {
743 /**
744 * The resolved vite config object
745 */
746 config: ResolvedConfig;
747 /**
748 * Stop the server.
749 */
750 close(): Promise<void>;
751 /**
752 * A connect app instance.
753 * - Can be used to attach custom middlewares to the preview server.
754 * - Can also be used as the handler function of a custom http server
755 * or as a middleware in any connect-style Node.js frameworks
756 *
757 * https://github.com/senchalabs/connect#use-middleware
758 */
759 middlewares: Connect.Server;
760 /**
761 * native Node http server instance
762 */
763 httpServer: HttpServer;
764 /**
765 * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
766 * if the server is not listening on any port.
767 */
768 resolvedUrls: ResolvedServerUrls | null;
769 /**
770 * Print server urls
771 */
772 printUrls(): void;
773 /**
774 * Bind CLI shortcuts
775 */
776 bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void;
777}
778type PreviewServerHook = (this: void, server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>;
779/**
780 * Starts the Vite server in preview mode, to simulate a production deployment
781 */
782declare function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>;
783
784type BindCLIShortcutsOptions<Server = ViteDevServer | PreviewServer> = {
785 /**
786 * Print a one-line shortcuts "help" hint to the terminal
787 */
788 print?: boolean;
789 /**
790 * Custom shortcuts to run when a key is pressed. These shortcuts take priority
791 * over the default shortcuts if they have the same keys (except the `h` key).
792 * To disable a default shortcut, define the same key but with `action: undefined`.
793 */
794 customShortcuts?: CLIShortcut<Server>[];
795};
796type CLIShortcut<Server = ViteDevServer | PreviewServer> = {
797 key: string;
798 description: string;
799 action?(server: Server): void | Promise<void>;
800};
801
802declare class PartialEnvironment {
803 name: string;
804 getTopLevelConfig(): ResolvedConfig;
805 config: ResolvedConfig & ResolvedEnvironmentOptions;
806 /**
807 * @deprecated use environment.config instead
808 **/
809 get options(): ResolvedEnvironmentOptions;
810 logger: Logger;
811 constructor(name: string, topLevelConfig: ResolvedConfig, options?: ResolvedEnvironmentOptions);
812}
813declare class BaseEnvironment extends PartialEnvironment {
814 get plugins(): Plugin[];
815 constructor(name: string, config: ResolvedConfig, options?: ResolvedEnvironmentOptions);
816}
817/**
818 * This class discourages users from inversely checking the `mode`
819 * to determine the type of environment, e.g.
820 *
821 * ```js
822 * const isDev = environment.mode !== 'build' // bad
823 * const isDev = environment.mode === 'dev' // good
824 * ```
825 *
826 * You should also not check against `"unknown"` specfically. It's
827 * a placeholder for more possible environment types.
828 */
829declare class UnknownEnvironment extends BaseEnvironment {
830 mode: "unknown";
831}
832
833declare class ScanEnvironment extends BaseEnvironment {
834 mode: "scan";
835 get pluginContainer(): EnvironmentPluginContainer;
836 init(): Promise<void>;
837}
838
839type ExportsData = {
840 hasModuleSyntax: boolean;
841 exports: readonly string[];
842 jsxLoader?: boolean;
843};
844interface DepsOptimizer {
845 init: () => Promise<void>;
846 metadata: DepOptimizationMetadata;
847 scanProcessing?: Promise<void>;
848 registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
849 run: () => void;
850 isOptimizedDepFile: (id: string) => boolean;
851 isOptimizedDepUrl: (url: string) => boolean;
852 getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
853 close: () => Promise<void>;
854 options: DepOptimizationOptions;
855}
856interface DepOptimizationConfig {
857 /**
858 * Force optimize listed dependencies (must be resolvable import paths,
859 * cannot be globs).
860 */
861 include?: string[];
862 /**
863 * Do not optimize these dependencies (must be resolvable import paths,
864 * cannot be globs).
865 */
866 exclude?: string[];
867 /**
868 * Forces ESM interop when importing these dependencies. Some legacy
869 * packages advertise themselves as ESM but use `require` internally
870 * @experimental
871 */
872 needsInterop?: string[];
873 /**
874 * Options to pass to esbuild during the dep scanning and optimization
875 *
876 * Certain options are omitted since changing them would not be compatible
877 * with Vite's dep optimization.
878 *
879 * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
880 * - `plugins` are merged with Vite's dep plugin
881 *
882 * https://esbuild.github.io/api
883 */
884 esbuildOptions?: Omit<esbuild_BuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
885 /**
886 * List of file extensions that can be optimized. A corresponding esbuild
887 * plugin must exist to handle the specific extension.
888 *
889 * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
890 * allows specifying additional extensions.
891 *
892 * @experimental
893 */
894 extensions?: string[];
895 /**
896 * Deps optimization during build was removed in Vite 5.1. This option is
897 * now redundant and will be removed in a future version. Switch to using
898 * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
899 * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
900 * @default 'build'
901 * @deprecated
902 * @experimental
903 */
904 disabled?: boolean | 'build' | 'dev';
905 /**
906 * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
907 * listed in `include` will be optimized. The scanner isn't run for cold start
908 * in this case. CJS-only dependencies must be present in `include` during dev.
909 * @default false
910 * @experimental
911 */
912 noDiscovery?: boolean;
913 /**
914 * When enabled, it will hold the first optimized deps results until all static
915 * imports are crawled on cold start. This avoids the need for full-page reloads
916 * when new dependencies are discovered and they trigger the generation of new
917 * common chunks. If all dependencies are found by the scanner plus the explicitly
918 * defined ones in `include`, it is better to disable this option to let the
919 * browser process more requests in parallel.
920 * @default true
921 * @experimental
922 */
923 holdUntilCrawlEnd?: boolean;
924}
925type DepOptimizationOptions = DepOptimizationConfig & {
926 /**
927 * By default, Vite will crawl your `index.html` to detect dependencies that
928 * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
929 * will crawl those entry points instead.
930 *
931 * If neither of these fit your needs, you can specify custom entries using
932 * this option - the value should be a tinyglobby pattern or array of patterns
933 * (https://github.com/SuperchupuDev/tinyglobby) that are relative from
934 * vite project root. This will overwrite default entries inference.
935 */
936 entries?: string | string[];
937 /**
938 * Force dep pre-optimization regardless of whether deps have changed.
939 * @experimental
940 */
941 force?: boolean;
942};
943interface OptimizedDepInfo {
944 id: string;
945 file: string;
946 src?: string;
947 needsInterop?: boolean;
948 browserHash?: string;
949 fileHash?: string;
950 /**
951 * During optimization, ids can still be resolved to their final location
952 * but the bundles may not yet be saved to disk
953 */
954 processing?: Promise<void>;
955 /**
956 * ExportData cache, discovered deps will parse the src entry to get exports
957 * data used both to define if interop is needed and when pre-bundling
958 */
959 exportsData?: Promise<ExportsData>;
960}
961interface DepOptimizationMetadata {
962 /**
963 * The main hash is determined by user config and dependency lockfiles.
964 * This is checked on server startup to avoid unnecessary re-bundles.
965 */
966 hash: string;
967 /**
968 * This hash is determined by dependency lockfiles.
969 * This is checked on server startup to avoid unnecessary re-bundles.
970 */
971 lockfileHash: string;
972 /**
973 * This hash is determined by user config.
974 * This is checked on server startup to avoid unnecessary re-bundles.
975 */
976 configHash: string;
977 /**
978 * The browser hash is determined by the main hash plus additional dependencies
979 * discovered at runtime. This is used to invalidate browser requests to
980 * optimized deps.
981 */
982 browserHash: string;
983 /**
984 * Metadata for each already optimized dependency
985 */
986 optimized: Record<string, OptimizedDepInfo>;
987 /**
988 * Metadata for non-entry optimized chunks and dynamic imports
989 */
990 chunks: Record<string, OptimizedDepInfo>;
991 /**
992 * Metadata for each newly discovered dependency after processing
993 */
994 discovered: Record<string, OptimizedDepInfo>;
995 /**
996 * OptimizedDepInfo list
997 */
998 depInfoList: OptimizedDepInfo[];
999}
1000/**
1001 * Scan and optimize dependencies within a project.
1002 * Used by Vite CLI when running `vite optimize`.
1003 */
1004declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
1005
1006interface TransformResult {
1007 code: string;
1008 map: SourceMap | {
1009 mappings: '';
1010 } | null;
1011 ssr?: boolean;
1012 etag?: string;
1013 deps?: string[];
1014 dynamicDeps?: string[];
1015}
1016interface TransformOptions {
1017 /**
1018 * @deprecated inferred from environment
1019 */
1020 ssr?: boolean;
1021}
1022
1023declare class EnvironmentModuleNode {
1024 environment: string;
1025 /**
1026 * Public served url path, starts with /
1027 */
1028 url: string;
1029 /**
1030 * Resolved file system path + query
1031 */
1032 id: string | null;
1033 file: string | null;
1034 type: 'js' | 'css';
1035 info?: ModuleInfo;
1036 meta?: Record<string, any>;
1037 importers: Set<EnvironmentModuleNode>;
1038 importedModules: Set<EnvironmentModuleNode>;
1039 acceptedHmrDeps: Set<EnvironmentModuleNode>;
1040 acceptedHmrExports: Set<string> | null;
1041 importedBindings: Map<string, Set<string>> | null;
1042 isSelfAccepting?: boolean;
1043 transformResult: TransformResult | null;
1044 ssrModule: Record<string, any> | null;
1045 ssrError: Error | null;
1046 lastHMRTimestamp: number;
1047 lastInvalidationTimestamp: number;
1048 /**
1049 * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
1050 */
1051 constructor(url: string, environment: string, setIsSelfAccepting?: boolean);
1052}
1053type ResolvedUrl = [
1054 url: string,
1055 resolvedId: string,
1056 meta: object | null | undefined
1057];
1058declare class EnvironmentModuleGraph {
1059 environment: string;
1060 urlToModuleMap: Map<string, EnvironmentModuleNode>;
1061 idToModuleMap: Map<string, EnvironmentModuleNode>;
1062 etagToModuleMap: Map<string, EnvironmentModuleNode>;
1063 fileToModulesMap: Map<string, Set<EnvironmentModuleNode>>;
1064 constructor(environment: string, resolveId: (url: string) => Promise<PartialResolvedId | null>);
1065 getModuleByUrl(rawUrl: string): Promise<EnvironmentModuleNode | undefined>;
1066 getModuleById(id: string): EnvironmentModuleNode | undefined;
1067 getModulesByFile(file: string): Set<EnvironmentModuleNode> | undefined;
1068 onFileChange(file: string): void;
1069 onFileDelete(file: string): void;
1070 invalidateModule(mod: EnvironmentModuleNode, seen?: Set<EnvironmentModuleNode>, timestamp?: number, isHmr?: boolean,
1071 ): void;
1072 invalidateAll(): void;
1073 /**
1074 * Update the module graph based on a module's updated imports information
1075 * If there are dependencies that no longer have any importers, they are
1076 * returned as a Set.
1077 *
1078 * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
1079 * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
1080 */
1081 updateModuleInfo(mod: EnvironmentModuleNode, importedModules: Set<string | EnvironmentModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | EnvironmentModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean,
1082 ): Promise<Set<EnvironmentModuleNode> | undefined>;
1083 ensureEntryFromUrl(rawUrl: string, setIsSelfAccepting?: boolean): Promise<EnvironmentModuleNode>;
1084 createFileOnlyEntry(file: string): EnvironmentModuleNode;
1085 resolveUrl(url: string): Promise<ResolvedUrl>;
1086 updateModuleTransformResult(mod: EnvironmentModuleNode, result: TransformResult | null): void;
1087 getModuleByEtag(etag: string): EnvironmentModuleNode | undefined;
1088}
1089
1090declare class ModuleNode {
1091 _moduleGraph: ModuleGraph;
1092 _clientModule: EnvironmentModuleNode | undefined;
1093 _ssrModule: EnvironmentModuleNode | undefined;
1094 constructor(moduleGraph: ModuleGraph, clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode);
1095 _get<T extends keyof EnvironmentModuleNode>(prop: T): EnvironmentModuleNode[T];
1096 _set<T extends keyof EnvironmentModuleNode>(prop: T, value: EnvironmentModuleNode[T]): void;
1097 _wrapModuleSet(prop: ModuleSetNames, module: EnvironmentModuleNode | undefined): Set<ModuleNode>;
1098 _getModuleSetUnion(prop: 'importedModules' | 'importers'): Set<ModuleNode>;
1099 _getModuleInfoUnion(prop: 'info'): ModuleInfo | undefined;
1100 _getModuleObjectUnion(prop: 'meta'): Record<string, any> | undefined;
1101 get url(): string;
1102 set url(value: string);
1103 get id(): string | null;
1104 set id(value: string | null);
1105 get file(): string | null;
1106 set file(value: string | null);
1107 get type(): 'js' | 'css';
1108 get info(): ModuleInfo | undefined;
1109 get meta(): Record<string, any> | undefined;
1110 get importers(): Set<ModuleNode>;
1111 get clientImportedModules(): Set<ModuleNode>;
1112 get ssrImportedModules(): Set<ModuleNode>;
1113 get importedModules(): Set<ModuleNode>;
1114 get acceptedHmrDeps(): Set<ModuleNode>;
1115 get acceptedHmrExports(): Set<string> | null;
1116 get importedBindings(): Map<string, Set<string>> | null;
1117 get isSelfAccepting(): boolean | undefined;
1118 get transformResult(): TransformResult | null;
1119 set transformResult(value: TransformResult | null);
1120 get ssrTransformResult(): TransformResult | null;
1121 set ssrTransformResult(value: TransformResult | null);
1122 get ssrModule(): Record<string, any> | null;
1123 get ssrError(): Error | null;
1124 get lastHMRTimestamp(): number;
1125 set lastHMRTimestamp(value: number);
1126 get lastInvalidationTimestamp(): number;
1127 get invalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1128 get ssrInvalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1129}
1130declare class ModuleGraph {
1131 urlToModuleMap: Map<string, ModuleNode>;
1132 idToModuleMap: Map<string, ModuleNode>;
1133 etagToModuleMap: Map<string, ModuleNode>;
1134 fileToModulesMap: Map<string, Set<ModuleNode>>;
1135 private moduleNodeCache;
1136 constructor(moduleGraphs: {
1137 client: () => EnvironmentModuleGraph;
1138 ssr: () => EnvironmentModuleGraph;
1139 });
1140 getModuleById(id: string): ModuleNode | undefined;
1141 getModuleByUrl(url: string, _ssr?: boolean): Promise<ModuleNode | undefined>;
1142 getModulesByFile(file: string): Set<ModuleNode> | undefined;
1143 onFileChange(file: string): void;
1144 onFileDelete(file: string): void;
1145 invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean,
1146 ): void;
1147 invalidateAll(): void;
1148 ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
1149 createFileOnlyEntry(file: string): ModuleNode;
1150 resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
1151 updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr?: boolean): void;
1152 getModuleByEtag(etag: string): ModuleNode | undefined;
1153 getBackwardCompatibleBrowserModuleNode(clientModule: EnvironmentModuleNode): ModuleNode;
1154 getBackwardCompatibleServerModuleNode(ssrModule: EnvironmentModuleNode): ModuleNode;
1155 getBackwardCompatibleModuleNode(mod: EnvironmentModuleNode): ModuleNode;
1156 getBackwardCompatibleModuleNodeDual(clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode): ModuleNode;
1157}
1158type ModuleSetNames = 'acceptedHmrDeps' | 'importedModules';
1159
1160interface HmrOptions {
1161 protocol?: string;
1162 host?: string;
1163 port?: number;
1164 clientPort?: number;
1165 path?: string;
1166 timeout?: number;
1167 overlay?: boolean;
1168 server?: HttpServer;
1169}
1170interface HotUpdateOptions {
1171 type: 'create' | 'update' | 'delete';
1172 file: string;
1173 timestamp: number;
1174 modules: Array<EnvironmentModuleNode>;
1175 read: () => string | Promise<string>;
1176 server: ViteDevServer;
1177 /**
1178 * @deprecated use this.environment in the hotUpdate hook instead
1179 **/
1180 environment: DevEnvironment;
1181}
1182interface HmrContext {
1183 file: string;
1184 timestamp: number;
1185 modules: Array<ModuleNode>;
1186 read: () => string | Promise<string>;
1187 server: ViteDevServer;
1188}
1189interface HotChannelClient {
1190 send(payload: HotPayload): void;
1191}
1192/** @deprecated use `HotChannelClient` instead */
1193type HMRBroadcasterClient = HotChannelClient;
1194type HotChannelListener<T extends string = string> = (data: InferCustomEventPayload<T>, client: HotChannelClient) => void;
1195interface HotChannel<Api = any> {
1196 /**
1197 * Broadcast events to all clients
1198 */
1199 send?(payload: HotPayload): void;
1200 /**
1201 * Handle custom event emitted by `import.meta.hot.send`
1202 */
1203 on?<T extends string>(event: T, listener: HotChannelListener<T>): void;
1204 on?(event: 'connection', listener: () => void): void;
1205 /**
1206 * Unregister event listener
1207 */
1208 off?(event: string, listener: Function): void;
1209 /**
1210 * Start listening for messages
1211 */
1212 listen?(): void;
1213 /**
1214 * Disconnect all clients, called when server is closed or restarted.
1215 */
1216 close?(): Promise<unknown> | void;
1217 api?: Api;
1218}
1219/** @deprecated use `HotChannel` instead */
1220type HMRChannel = HotChannel;
1221interface NormalizedHotChannelClient {
1222 /**
1223 * Send event to the client
1224 */
1225 send(payload: HotPayload): void;
1226 /**
1227 * Send custom event
1228 */
1229 send(event: string, payload?: CustomPayload['data']): void;
1230}
1231interface NormalizedHotChannel<Api = any> {
1232 /**
1233 * Broadcast events to all clients
1234 */
1235 send(payload: HotPayload): void;
1236 /**
1237 * Send custom event
1238 */
1239 send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
1240 /**
1241 * Handle custom event emitted by `import.meta.hot.send`
1242 */
1243 on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: NormalizedHotChannelClient) => void): void;
1244 on(event: 'connection', listener: () => void): void;
1245 /**
1246 * Unregister event listener
1247 */
1248 off(event: string, listener: Function): void;
1249 handleInvoke(payload: HotPayload): Promise<{
1250 result: any;
1251 } | {
1252 error: any;
1253 }>;
1254 /**
1255 * Start listening for messages
1256 */
1257 listen(): void;
1258 /**
1259 * Disconnect all clients, called when server is closed or restarted.
1260 */
1261 close(): Promise<unknown> | void;
1262 api?: Api;
1263}
1264type ServerHotChannelApi = {
1265 innerEmitter: EventEmitter;
1266 outsideEmitter: EventEmitter;
1267};
1268type ServerHotChannel = HotChannel<ServerHotChannelApi>;
1269/** @deprecated use `ServerHotChannel` instead */
1270type ServerHMRChannel = ServerHotChannel;
1271declare function createServerHotChannel(): ServerHotChannel;
1272/** @deprecated use `environment.hot` instead */
1273interface HotBroadcaster extends NormalizedHotChannel {
1274 readonly channels: NormalizedHotChannel[];
1275 /**
1276 * A noop.
1277 * @deprecated
1278 */
1279 addChannel(channel: HotChannel): HotBroadcaster;
1280 close(): Promise<unknown[]>;
1281}
1282/** @deprecated use `environment.hot` instead */
1283type HMRBroadcaster = HotBroadcaster;
1284
1285// Modified and inlined to avoid extra dependency
1286// Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
1287
1288declare const WebSocketAlias: typeof WebSocket
1289interface WebSocketAlias extends WebSocket {}
1290
1291// WebSocket socket.
1292declare class WebSocket extends EventEmitter {
1293 /** The connection is not yet open. */
1294 static readonly CONNECTING: 0
1295 /** The connection is open and ready to communicate. */
1296 static readonly OPEN: 1
1297 /** The connection is in the process of closing. */
1298 static readonly CLOSING: 2
1299 /** The connection is closed. */
1300 static readonly CLOSED: 3
1301
1302 binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
1303 readonly bufferedAmount: number
1304 readonly extensions: string
1305 /** Indicates whether the websocket is paused */
1306 readonly isPaused: boolean
1307 readonly protocol: string
1308 /** The current state of the connection */
1309 readonly readyState:
1310 | typeof WebSocket.CONNECTING
1311 | typeof WebSocket.OPEN
1312 | typeof WebSocket.CLOSING
1313 | typeof WebSocket.CLOSED
1314 readonly url: string
1315
1316 /** The connection is not yet open. */
1317 readonly CONNECTING: 0
1318 /** The connection is open and ready to communicate. */
1319 readonly OPEN: 1
1320 /** The connection is in the process of closing. */
1321 readonly CLOSING: 2
1322 /** The connection is closed. */
1323 readonly CLOSED: 3
1324
1325 onopen: ((event: WebSocket.Event) => void) | null
1326 onerror: ((event: WebSocket.ErrorEvent) => void) | null
1327 onclose: ((event: WebSocket.CloseEvent) => void) | null
1328 onmessage: ((event: WebSocket.MessageEvent) => void) | null
1329
1330 constructor(address: null)
1331 constructor(
1332 address: string | URL,
1333 options?: WebSocket.ClientOptions | ClientRequestArgs,
1334 )
1335 constructor(
1336 address: string | URL,
1337 protocols?: string | string[],
1338 options?: WebSocket.ClientOptions | ClientRequestArgs,
1339 )
1340
1341 close(code?: number, data?: string | Buffer): void
1342 ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
1343 pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
1344 send(data: any, cb?: (err?: Error) => void): void
1345 send(
1346 data: any,
1347 options: {
1348 mask?: boolean | undefined
1349 binary?: boolean | undefined
1350 compress?: boolean | undefined
1351 fin?: boolean | undefined
1352 },
1353 cb?: (err?: Error) => void,
1354 ): void
1355 terminate(): void
1356
1357 /**
1358 * Pause the websocket causing it to stop emitting events. Some events can still be
1359 * emitted after this is called, until all buffered data is consumed. This method
1360 * is a noop if the ready state is `CONNECTING` or `CLOSED`.
1361 */
1362 pause(): void
1363 /**
1364 * Make a paused socket resume emitting events. This method is a noop if the ready
1365 * state is `CONNECTING` or `CLOSED`.
1366 */
1367 resume(): void
1368
1369 // HTML5 WebSocket events
1370 addEventListener(
1371 method: 'message',
1372 cb: (event: WebSocket.MessageEvent) => void,
1373 options?: WebSocket.EventListenerOptions,
1374 ): void
1375 addEventListener(
1376 method: 'close',
1377 cb: (event: WebSocket.CloseEvent) => void,
1378 options?: WebSocket.EventListenerOptions,
1379 ): void
1380 addEventListener(
1381 method: 'error',
1382 cb: (event: WebSocket.ErrorEvent) => void,
1383 options?: WebSocket.EventListenerOptions,
1384 ): void
1385 addEventListener(
1386 method: 'open',
1387 cb: (event: WebSocket.Event) => void,
1388 options?: WebSocket.EventListenerOptions,
1389 ): void
1390
1391 removeEventListener(
1392 method: 'message',
1393 cb: (event: WebSocket.MessageEvent) => void,
1394 ): void
1395 removeEventListener(
1396 method: 'close',
1397 cb: (event: WebSocket.CloseEvent) => void,
1398 ): void
1399 removeEventListener(
1400 method: 'error',
1401 cb: (event: WebSocket.ErrorEvent) => void,
1402 ): void
1403 removeEventListener(
1404 method: 'open',
1405 cb: (event: WebSocket.Event) => void,
1406 ): void
1407
1408 // Events
1409 on(
1410 event: 'close',
1411 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1412 ): this
1413 on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1414 on(
1415 event: 'upgrade',
1416 listener: (this: WebSocket, request: IncomingMessage) => void,
1417 ): this
1418 on(
1419 event: 'message',
1420 listener: (
1421 this: WebSocket,
1422 data: WebSocket.RawData,
1423 isBinary: boolean,
1424 ) => void,
1425 ): this
1426 on(event: 'open', listener: (this: WebSocket) => void): this
1427 on(
1428 event: 'ping' | 'pong',
1429 listener: (this: WebSocket, data: Buffer) => void,
1430 ): this
1431 on(
1432 event: 'unexpected-response',
1433 listener: (
1434 this: WebSocket,
1435 request: ClientRequest,
1436 response: IncomingMessage,
1437 ) => void,
1438 ): this
1439 on(
1440 event: string | symbol,
1441 listener: (this: WebSocket, ...args: any[]) => void,
1442 ): this
1443
1444 once(
1445 event: 'close',
1446 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1447 ): this
1448 once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1449 once(
1450 event: 'upgrade',
1451 listener: (this: WebSocket, request: IncomingMessage) => void,
1452 ): this
1453 once(
1454 event: 'message',
1455 listener: (
1456 this: WebSocket,
1457 data: WebSocket.RawData,
1458 isBinary: boolean,
1459 ) => void,
1460 ): this
1461 once(event: 'open', listener: (this: WebSocket) => void): this
1462 once(
1463 event: 'ping' | 'pong',
1464 listener: (this: WebSocket, data: Buffer) => void,
1465 ): this
1466 once(
1467 event: 'unexpected-response',
1468 listener: (
1469 this: WebSocket,
1470 request: ClientRequest,
1471 response: IncomingMessage,
1472 ) => void,
1473 ): this
1474 once(
1475 event: string | symbol,
1476 listener: (this: WebSocket, ...args: any[]) => void,
1477 ): this
1478
1479 off(
1480 event: 'close',
1481 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1482 ): this
1483 off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1484 off(
1485 event: 'upgrade',
1486 listener: (this: WebSocket, request: IncomingMessage) => void,
1487 ): this
1488 off(
1489 event: 'message',
1490 listener: (
1491 this: WebSocket,
1492 data: WebSocket.RawData,
1493 isBinary: boolean,
1494 ) => void,
1495 ): this
1496 off(event: 'open', listener: (this: WebSocket) => void): this
1497 off(
1498 event: 'ping' | 'pong',
1499 listener: (this: WebSocket, data: Buffer) => void,
1500 ): this
1501 off(
1502 event: 'unexpected-response',
1503 listener: (
1504 this: WebSocket,
1505 request: ClientRequest,
1506 response: IncomingMessage,
1507 ) => void,
1508 ): this
1509 off(
1510 event: string | symbol,
1511 listener: (this: WebSocket, ...args: any[]) => void,
1512 ): this
1513
1514 addListener(
1515 event: 'close',
1516 listener: (code: number, reason: Buffer) => void,
1517 ): this
1518 addListener(event: 'error', listener: (err: Error) => void): this
1519 addListener(
1520 event: 'upgrade',
1521 listener: (request: IncomingMessage) => void,
1522 ): this
1523 addListener(
1524 event: 'message',
1525 listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1526 ): this
1527 addListener(event: 'open', listener: () => void): this
1528 addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1529 addListener(
1530 event: 'unexpected-response',
1531 listener: (request: ClientRequest, response: IncomingMessage) => void,
1532 ): this
1533 addListener(event: string | symbol, listener: (...args: any[]) => void): this
1534
1535 removeListener(
1536 event: 'close',
1537 listener: (code: number, reason: Buffer) => void,
1538 ): this
1539 removeListener(event: 'error', listener: (err: Error) => void): this
1540 removeListener(
1541 event: 'upgrade',
1542 listener: (request: IncomingMessage) => void,
1543 ): this
1544 removeListener(
1545 event: 'message',
1546 listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1547 ): this
1548 removeListener(event: 'open', listener: () => void): this
1549 removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1550 removeListener(
1551 event: 'unexpected-response',
1552 listener: (request: ClientRequest, response: IncomingMessage) => void,
1553 ): this
1554 removeListener(
1555 event: string | symbol,
1556 listener: (...args: any[]) => void,
1557 ): this
1558}
1559
1560declare namespace WebSocket {
1561 /**
1562 * Data represents the raw message payload received over the WebSocket.
1563 */
1564 type RawData = Buffer | ArrayBuffer | Buffer[]
1565
1566 /**
1567 * Data represents the message payload received over the WebSocket.
1568 */
1569 type Data = string | Buffer | ArrayBuffer | Buffer[]
1570
1571 /**
1572 * CertMeta represents the accepted types for certificate & key data.
1573 */
1574 type CertMeta = string | string[] | Buffer | Buffer[]
1575
1576 /**
1577 * VerifyClientCallbackSync is a synchronous callback used to inspect the
1578 * incoming message. The return value (boolean) of the function determines
1579 * whether or not to accept the handshake.
1580 */
1581 type VerifyClientCallbackSync = (info: {
1582 origin: string
1583 secure: boolean
1584 req: IncomingMessage
1585 }) => boolean
1586
1587 /**
1588 * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
1589 * incoming message. The return value (boolean) of the function determines
1590 * whether or not to accept the handshake.
1591 */
1592 type VerifyClientCallbackAsync = (
1593 info: { origin: string; secure: boolean; req: IncomingMessage },
1594 callback: (
1595 res: boolean,
1596 code?: number,
1597 message?: string,
1598 headers?: OutgoingHttpHeaders,
1599 ) => void,
1600 ) => void
1601
1602 interface ClientOptions extends SecureContextOptions {
1603 protocol?: string | undefined
1604 followRedirects?: boolean | undefined
1605 generateMask?(mask: Buffer): void
1606 handshakeTimeout?: number | undefined
1607 maxRedirects?: number | undefined
1608 perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1609 localAddress?: string | undefined
1610 protocolVersion?: number | undefined
1611 headers?: { [key: string]: string } | undefined
1612 origin?: string | undefined
1613 agent?: Agent | undefined
1614 host?: string | undefined
1615 family?: number | undefined
1616 checkServerIdentity?(servername: string, cert: CertMeta): boolean
1617 rejectUnauthorized?: boolean | undefined
1618 maxPayload?: number | undefined
1619 skipUTF8Validation?: boolean | undefined
1620 }
1621
1622 interface PerMessageDeflateOptions {
1623 serverNoContextTakeover?: boolean | undefined
1624 clientNoContextTakeover?: boolean | undefined
1625 serverMaxWindowBits?: number | undefined
1626 clientMaxWindowBits?: number | undefined
1627 zlibDeflateOptions?:
1628 | {
1629 flush?: number | undefined
1630 finishFlush?: number | undefined
1631 chunkSize?: number | undefined
1632 windowBits?: number | undefined
1633 level?: number | undefined
1634 memLevel?: number | undefined
1635 strategy?: number | undefined
1636 dictionary?: Buffer | Buffer[] | DataView | undefined
1637 info?: boolean | undefined
1638 }
1639 | undefined
1640 zlibInflateOptions?: ZlibOptions | undefined
1641 threshold?: number | undefined
1642 concurrencyLimit?: number | undefined
1643 }
1644
1645 interface Event {
1646 type: string
1647 target: WebSocket
1648 }
1649
1650 interface ErrorEvent {
1651 error: any
1652 message: string
1653 type: string
1654 target: WebSocket
1655 }
1656
1657 interface CloseEvent {
1658 wasClean: boolean
1659 code: number
1660 reason: string
1661 type: string
1662 target: WebSocket
1663 }
1664
1665 interface MessageEvent {
1666 data: Data
1667 type: string
1668 target: WebSocket
1669 }
1670
1671 interface EventListenerOptions {
1672 once?: boolean | undefined
1673 }
1674
1675 interface ServerOptions {
1676 host?: string | undefined
1677 port?: number | undefined
1678 backlog?: number | undefined
1679 server?: Server | HttpsServer | undefined
1680 verifyClient?:
1681 | VerifyClientCallbackAsync
1682 | VerifyClientCallbackSync
1683 | undefined
1684 handleProtocols?: (
1685 protocols: Set<string>,
1686 request: IncomingMessage,
1687 ) => string | false
1688 path?: string | undefined
1689 noServer?: boolean | undefined
1690 clientTracking?: boolean | undefined
1691 perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1692 maxPayload?: number | undefined
1693 skipUTF8Validation?: boolean | undefined
1694 WebSocket?: typeof WebSocket.WebSocket | undefined
1695 }
1696
1697 interface AddressInfo {
1698 address: string
1699 family: string
1700 port: number
1701 }
1702
1703 // WebSocket Server
1704 class Server<T extends WebSocket = WebSocket> extends EventEmitter {
1705 options: ServerOptions
1706 path: string
1707 clients: Set<T>
1708
1709 constructor(options?: ServerOptions, callback?: () => void)
1710
1711 address(): AddressInfo | string
1712 close(cb?: (err?: Error) => void): void
1713 handleUpgrade(
1714 request: IncomingMessage,
1715 socket: Duplex,
1716 upgradeHead: Buffer,
1717 callback: (client: T, request: IncomingMessage) => void,
1718 ): void
1719 shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
1720
1721 // Events
1722 on(
1723 event: 'connection',
1724 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1725 ): this
1726 on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1727 on(
1728 event: 'headers',
1729 cb: (
1730 this: Server<T>,
1731 headers: string[],
1732 request: IncomingMessage,
1733 ) => void,
1734 ): this
1735 on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1736 on(
1737 event: string | symbol,
1738 listener: (this: Server<T>, ...args: any[]) => void,
1739 ): this
1740
1741 once(
1742 event: 'connection',
1743 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1744 ): this
1745 once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1746 once(
1747 event: 'headers',
1748 cb: (
1749 this: Server<T>,
1750 headers: string[],
1751 request: IncomingMessage,
1752 ) => void,
1753 ): this
1754 once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1755 once(
1756 event: string | symbol,
1757 listener: (this: Server<T>, ...args: any[]) => void,
1758 ): this
1759
1760 off(
1761 event: 'connection',
1762 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1763 ): this
1764 off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1765 off(
1766 event: 'headers',
1767 cb: (
1768 this: Server<T>,
1769 headers: string[],
1770 request: IncomingMessage,
1771 ) => void,
1772 ): this
1773 off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1774 off(
1775 event: string | symbol,
1776 listener: (this: Server<T>, ...args: any[]) => void,
1777 ): this
1778
1779 addListener(
1780 event: 'connection',
1781 cb: (client: T, request: IncomingMessage) => void,
1782 ): this
1783 addListener(event: 'error', cb: (err: Error) => void): this
1784 addListener(
1785 event: 'headers',
1786 cb: (headers: string[], request: IncomingMessage) => void,
1787 ): this
1788 addListener(event: 'close' | 'listening', cb: () => void): this
1789 addListener(
1790 event: string | symbol,
1791 listener: (...args: any[]) => void,
1792 ): this
1793
1794 removeListener(event: 'connection', cb: (client: T) => void): this
1795 removeListener(event: 'error', cb: (err: Error) => void): this
1796 removeListener(
1797 event: 'headers',
1798 cb: (headers: string[], request: IncomingMessage) => void,
1799 ): this
1800 removeListener(event: 'close' | 'listening', cb: () => void): this
1801 removeListener(
1802 event: string | symbol,
1803 listener: (...args: any[]) => void,
1804 ): this
1805 }
1806
1807 const WebSocketServer: typeof Server
1808 interface WebSocketServer extends Server {}
1809 const WebSocket: typeof WebSocketAlias
1810 interface WebSocket extends WebSocketAlias {}
1811
1812 // WebSocket stream
1813 function createWebSocketStream(
1814 websocket: WebSocket,
1815 options?: DuplexOptions,
1816 ): Duplex
1817}
1818
1819type WebSocketCustomListener<T> = (data: T, client: WebSocketClient, invoke?: 'send' | `send:${string}`) => void;
1820declare const isWebSocketServer: unique symbol;
1821interface WebSocketServer extends NormalizedHotChannel {
1822 /**
1823 * Handle custom event emitted by `import.meta.hot.send`
1824 */
1825 on: WebSocket.Server['on'] & {
1826 <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
1827 };
1828 /**
1829 * Unregister event listener.
1830 */
1831 off: WebSocket.Server['off'] & {
1832 (event: string, listener: Function): void;
1833 };
1834 /**
1835 * Listen on port and host
1836 */
1837 listen(): void;
1838 /**
1839 * Disconnect all clients and terminate the server.
1840 */
1841 close(): Promise<void>;
1842 [isWebSocketServer]: true;
1843 /**
1844 * Get all connected clients.
1845 */
1846 clients: Set<WebSocketClient>;
1847}
1848interface WebSocketClient extends NormalizedHotChannelClient {
1849 /**
1850 * The raw WebSocket instance
1851 * @advanced
1852 */
1853 socket: WebSocket;
1854}
1855
1856interface DevEnvironmentContext {
1857 hot: boolean;
1858 transport?: HotChannel | WebSocketServer;
1859 options?: EnvironmentOptions;
1860 remoteRunner?: {
1861 inlineSourceMap?: boolean;
1862 };
1863 depsOptimizer?: DepsOptimizer;
1864}
1865declare class DevEnvironment extends BaseEnvironment {
1866 mode: "dev";
1867 moduleGraph: EnvironmentModuleGraph;
1868 depsOptimizer?: DepsOptimizer;
1869 get pluginContainer(): EnvironmentPluginContainer;
1870 /**
1871 * Hot channel for this environment. If not provided or disabled,
1872 * it will be a noop channel that does nothing.
1873 *
1874 * @example
1875 * environment.hot.send({ type: 'full-reload' })
1876 */
1877 hot: NormalizedHotChannel;
1878 constructor(name: string, config: ResolvedConfig, context: DevEnvironmentContext);
1879 init(options?: {
1880 watcher?: FSWatcher;
1881 /**
1882 * the previous instance used for the environment with the same name
1883 *
1884 * when using, the consumer should check if it's an instance generated from the same class or factory function
1885 */
1886 previousInstance?: DevEnvironment;
1887 }): Promise<void>;
1888 /**
1889 * When the dev server is restarted, the methods are called in the following order:
1890 * - new instance `init`
1891 * - previous instance `close`
1892 * - new instance `listen`
1893 */
1894 listen(server: ViteDevServer): Promise<void>;
1895 fetchModule(id: string, importer?: string, options?: FetchFunctionOptions): Promise<FetchResult>;
1896 reloadModule(module: EnvironmentModuleNode): Promise<void>;
1897 transformRequest(url: string): Promise<TransformResult | null>;
1898 warmupRequest(url: string): Promise<void>;
1899 close(): Promise<void>;
1900 /**
1901 * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
1902 * are processed after the first transformRequest call. If called from a load or transform
1903 * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
1904 * Calling this function after the first static imports section of the module graph has been
1905 * processed will resolve immediately.
1906 * @experimental
1907 */
1908 waitForRequestsIdle(ignoredId?: string): Promise<void>;
1909}
1910
1911interface RollupCommonJSOptions {
1912 /**
1913 * A minimatch pattern, or array of patterns, which specifies the files in
1914 * the build the plugin should operate on. By default, all files with
1915 * extension `".cjs"` or those in `extensions` are included, but you can
1916 * narrow this list by only including specific files. These files will be
1917 * analyzed and transpiled if either the analysis does not find ES module
1918 * specific statements or `transformMixedEsModules` is `true`.
1919 * @default undefined
1920 */
1921 include?: string | RegExp | readonly (string | RegExp)[]
1922 /**
1923 * A minimatch pattern, or array of patterns, which specifies the files in
1924 * the build the plugin should _ignore_. By default, all files with
1925 * extensions other than those in `extensions` or `".cjs"` are ignored, but you
1926 * can exclude additional files. See also the `include` option.
1927 * @default undefined
1928 */
1929 exclude?: string | RegExp | readonly (string | RegExp)[]
1930 /**
1931 * For extensionless imports, search for extensions other than .js in the
1932 * order specified. Note that you need to make sure that non-JavaScript files
1933 * are transpiled by another plugin first.
1934 * @default [ '.js' ]
1935 */
1936 extensions?: ReadonlyArray<string>
1937 /**
1938 * If true then uses of `global` won't be dealt with by this plugin
1939 * @default false
1940 */
1941 ignoreGlobal?: boolean
1942 /**
1943 * If false, skips source map generation for CommonJS modules. This will
1944 * improve performance.
1945 * @default true
1946 */
1947 sourceMap?: boolean
1948 /**
1949 * Some `require` calls cannot be resolved statically to be translated to
1950 * imports.
1951 * When this option is set to `false`, the generated code will either
1952 * directly throw an error when such a call is encountered or, when
1953 * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
1954 * configured dynamic require target.
1955 * Setting this option to `true` will instead leave the `require` call in the
1956 * code or use it as a fallback for `dynamicRequireTargets`.
1957 * @default false
1958 */
1959 ignoreDynamicRequires?: boolean
1960 /**
1961 * Instructs the plugin whether to enable mixed module transformations. This
1962 * is useful in scenarios with modules that contain a mix of ES `import`
1963 * statements and CommonJS `require` expressions. Set to `true` if `require`
1964 * calls should be transformed to imports in mixed modules, or `false` if the
1965 * `require` expressions should survive the transformation. The latter can be
1966 * important if the code contains environment detection, or you are coding
1967 * for an environment with special treatment for `require` calls such as
1968 * ElectronJS. See also the `ignore` option.
1969 * @default false
1970 */
1971 transformMixedEsModules?: boolean
1972 /**
1973 * By default, this plugin will try to hoist `require` statements as imports
1974 * to the top of each file. While this works well for many code bases and
1975 * allows for very efficient ESM output, it does not perfectly capture
1976 * CommonJS semantics as the order of side effects like log statements may
1977 * change. But it is especially problematic when there are circular `require`
1978 * calls between CommonJS modules as those often rely on the lazy execution of
1979 * nested `require` calls.
1980 *
1981 * Setting this option to `true` will wrap all CommonJS files in functions
1982 * which are executed when they are required for the first time, preserving
1983 * NodeJS semantics. Note that this can have an impact on the size and
1984 * performance of the generated code.
1985 *
1986 * The default value of `"auto"` will only wrap CommonJS files when they are
1987 * part of a CommonJS dependency cycle, e.g. an index file that is required by
1988 * many of its dependencies. All other CommonJS files are hoisted. This is the
1989 * recommended setting for most code bases.
1990 *
1991 * `false` will entirely prevent wrapping and hoist all files. This may still
1992 * work depending on the nature of cyclic dependencies but will often cause
1993 * problems.
1994 *
1995 * You can also provide a minimatch pattern, or array of patterns, to only
1996 * specify a subset of files which should be wrapped in functions for proper
1997 * `require` semantics.
1998 *
1999 * `"debug"` works like `"auto"` but after bundling, it will display a warning
2000 * containing a list of ids that have been wrapped which can be used as
2001 * minimatch pattern for fine-tuning.
2002 * @default "auto"
2003 */
2004 strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
2005 /**
2006 * Sometimes you have to leave require statements unconverted. Pass an array
2007 * containing the IDs or a `id => boolean` function.
2008 * @default []
2009 */
2010 ignore?: ReadonlyArray<string> | ((id: string) => boolean)
2011 /**
2012 * In most cases, where `require` calls are inside a `try-catch` clause,
2013 * they should be left unconverted as it requires an optional dependency
2014 * that may or may not be installed beside the rolled up package.
2015 * Due to the conversion of `require` to a static `import` - the call is
2016 * hoisted to the top of the file, outside the `try-catch` clause.
2017 *
2018 * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
2019 * - `false`: All `require` calls inside a `try` will be converted as if the
2020 * `try-catch` clause is not there.
2021 * - `remove`: Remove all `require` calls from inside any `try` block.
2022 * - `string[]`: Pass an array containing the IDs to left unconverted.
2023 * - `((id: string) => boolean|'remove')`: Pass a function that controls
2024 * individual IDs.
2025 *
2026 * @default true
2027 */
2028 ignoreTryCatch?:
2029 | boolean
2030 | 'remove'
2031 | ReadonlyArray<string>
2032 | ((id: string) => boolean | 'remove')
2033 /**
2034 * Controls how to render imports from external dependencies. By default,
2035 * this plugin assumes that all external dependencies are CommonJS. This
2036 * means they are rendered as default imports to be compatible with e.g.
2037 * NodeJS where ES modules can only import a default export from a CommonJS
2038 * dependency.
2039 *
2040 * If you set `esmExternals` to `true`, this plugin assumes that all
2041 * external dependencies are ES modules and respect the
2042 * `requireReturnsDefault` option. If that option is not set, they will be
2043 * rendered as namespace imports.
2044 *
2045 * You can also supply an array of ids to be treated as ES modules, or a
2046 * function that will be passed each external id to determine whether it is
2047 * an ES module.
2048 * @default false
2049 */
2050 esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
2051 /**
2052 * Controls what is returned when requiring an ES module from a CommonJS file.
2053 * When using the `esmExternals` option, this will also apply to external
2054 * modules. By default, this plugin will render those imports as namespace
2055 * imports i.e.
2056 *
2057 * ```js
2058 * // input
2059 * const foo = require('foo');
2060 *
2061 * // output
2062 * import * as foo from 'foo';
2063 * ```
2064 *
2065 * However, there are some situations where this may not be desired.
2066 * For these situations, you can change Rollup's behaviour either globally or
2067 * per module. To change it globally, set the `requireReturnsDefault` option
2068 * to one of the following values:
2069 *
2070 * - `false`: This is the default, requiring an ES module returns its
2071 * namespace. This is the only option that will also add a marker
2072 * `__esModule: true` to the namespace to support interop patterns in
2073 * CommonJS modules that are transpiled ES modules.
2074 * - `"namespace"`: Like `false`, requiring an ES module returns its
2075 * namespace, but the plugin does not add the `__esModule` marker and thus
2076 * creates more efficient code. For external dependencies when using
2077 * `esmExternals: true`, no additional interop code is generated.
2078 * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
2079 * Rollup: If a module has a default export and no named exports, requiring
2080 * that module returns the default export. In all other cases, the namespace
2081 * is returned. For external dependencies when using `esmExternals: true`, a
2082 * corresponding interop helper is added.
2083 * - `"preferred"`: If a module has a default export, requiring that module
2084 * always returns the default export, no matter whether additional named
2085 * exports exist. This is similar to how previous versions of this plugin
2086 * worked. Again for external dependencies when using `esmExternals: true`,
2087 * an interop helper is added.
2088 * - `true`: This will always try to return the default export on require
2089 * without checking if it actually exists. This can throw at build time if
2090 * there is no default export. This is how external dependencies are handled
2091 * when `esmExternals` is not used. The advantage over the other options is
2092 * that, like `false`, this does not add an interop helper for external
2093 * dependencies, keeping the code lean.
2094 *
2095 * To change this for individual modules, you can supply a function for
2096 * `requireReturnsDefault` instead. This function will then be called once for
2097 * each required ES module or external dependency with the corresponding id
2098 * and allows you to return different values for different modules.
2099 * @default false
2100 */
2101 requireReturnsDefault?:
2102 | boolean
2103 | 'auto'
2104 | 'preferred'
2105 | 'namespace'
2106 | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
2107
2108 /**
2109 * @default "auto"
2110 */
2111 defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
2112 /**
2113 * Some modules contain dynamic `require` calls, or require modules that
2114 * contain circular dependencies, which are not handled well by static
2115 * imports. Including those modules as `dynamicRequireTargets` will simulate a
2116 * CommonJS (NodeJS-like) environment for them with support for dynamic
2117 * dependencies. It also enables `strictRequires` for those modules.
2118 *
2119 * Note: In extreme cases, this feature may result in some paths being
2120 * rendered as absolute in the final bundle. The plugin tries to avoid
2121 * exposing paths from the local machine, but if you are `dynamicRequirePaths`
2122 * with paths that are far away from your project's folder, that may require
2123 * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
2124 */
2125 dynamicRequireTargets?: string | ReadonlyArray<string>
2126 /**
2127 * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
2128 * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
2129 * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
2130 * home directory name. By default, it uses the current working directory.
2131 */
2132 dynamicRequireRoot?: string
2133}
2134
2135interface RollupDynamicImportVarsOptions {
2136 /**
2137 * Files to include in this plugin (default all).
2138 * @default []
2139 */
2140 include?: string | RegExp | (string | RegExp)[]
2141 /**
2142 * Files to exclude in this plugin (default none).
2143 * @default []
2144 */
2145 exclude?: string | RegExp | (string | RegExp)[]
2146 /**
2147 * 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.
2148 * @default false
2149 */
2150 warnOnError?: boolean
2151}
2152
2153// Modified and inlined to avoid extra dependency
2154// Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
2155// BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
2156
2157declare namespace Terser {
2158 export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
2159
2160 export type ConsoleProperty = keyof typeof console
2161 type DropConsoleOption = boolean | ConsoleProperty[]
2162
2163 export interface ParseOptions {
2164 bare_returns?: boolean
2165 /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
2166 ecma?: ECMA
2167 html5_comments?: boolean
2168 shebang?: boolean
2169 }
2170
2171 export interface CompressOptions {
2172 arguments?: boolean
2173 arrows?: boolean
2174 booleans_as_integers?: boolean
2175 booleans?: boolean
2176 collapse_vars?: boolean
2177 comparisons?: boolean
2178 computed_props?: boolean
2179 conditionals?: boolean
2180 dead_code?: boolean
2181 defaults?: boolean
2182 directives?: boolean
2183 drop_console?: DropConsoleOption
2184 drop_debugger?: boolean
2185 ecma?: ECMA
2186 evaluate?: boolean
2187 expression?: boolean
2188 global_defs?: object
2189 hoist_funs?: boolean
2190 hoist_props?: boolean
2191 hoist_vars?: boolean
2192 ie8?: boolean
2193 if_return?: boolean
2194 inline?: boolean | InlineFunctions
2195 join_vars?: boolean
2196 keep_classnames?: boolean | RegExp
2197 keep_fargs?: boolean
2198 keep_fnames?: boolean | RegExp
2199 keep_infinity?: boolean
2200 loops?: boolean
2201 module?: boolean
2202 negate_iife?: boolean
2203 passes?: number
2204 properties?: boolean
2205 pure_funcs?: string[]
2206 pure_new?: boolean
2207 pure_getters?: boolean | 'strict'
2208 reduce_funcs?: boolean
2209 reduce_vars?: boolean
2210 sequences?: boolean | number
2211 side_effects?: boolean
2212 switches?: boolean
2213 toplevel?: boolean
2214 top_retain?: null | string | string[] | RegExp
2215 typeofs?: boolean
2216 unsafe_arrows?: boolean
2217 unsafe?: boolean
2218 unsafe_comps?: boolean
2219 unsafe_Function?: boolean
2220 unsafe_math?: boolean
2221 unsafe_symbols?: boolean
2222 unsafe_methods?: boolean
2223 unsafe_proto?: boolean
2224 unsafe_regexp?: boolean
2225 unsafe_undefined?: boolean
2226 unused?: boolean
2227 }
2228
2229 export enum InlineFunctions {
2230 Disabled = 0,
2231 SimpleFunctions = 1,
2232 WithArguments = 2,
2233 WithArgumentsAndVariables = 3,
2234 }
2235
2236 export interface MangleOptions {
2237 eval?: boolean
2238 keep_classnames?: boolean | RegExp
2239 keep_fnames?: boolean | RegExp
2240 module?: boolean
2241 nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2242 properties?: boolean | ManglePropertiesOptions
2243 reserved?: string[]
2244 safari10?: boolean
2245 toplevel?: boolean
2246 }
2247
2248 /**
2249 * An identifier mangler for which the output is invariant with respect to the source code.
2250 */
2251 export interface SimpleIdentifierMangler {
2252 /**
2253 * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
2254 * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
2255 * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
2256 * @param n The ordinal of the identifier.
2257 */
2258 get(n: number): string
2259 }
2260
2261 /**
2262 * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
2263 */
2264 export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
2265 /**
2266 * Modifies the internal weighting of the input characters by the specified delta.
2267 * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
2268 * @param chars The characters to modify the weighting of.
2269 * @param delta The numeric weight to add to the characters.
2270 */
2271 consider(chars: string, delta: number): number
2272 /**
2273 * Resets character weights.
2274 */
2275 reset(): void
2276 /**
2277 * Sorts identifiers by character frequency, in preparation for calls to get(n).
2278 */
2279 sort(): void
2280 }
2281
2282 export interface ManglePropertiesOptions {
2283 builtins?: boolean
2284 debug?: boolean
2285 keep_quoted?: boolean | 'strict'
2286 nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2287 regex?: RegExp | string
2288 reserved?: string[]
2289 }
2290
2291 export interface FormatOptions {
2292 ascii_only?: boolean
2293 /** @deprecated Not implemented anymore */
2294 beautify?: boolean
2295 braces?: boolean
2296 comments?:
2297 | boolean
2298 | 'all'
2299 | 'some'
2300 | RegExp
2301 | ((
2302 node: any,
2303 comment: {
2304 value: string
2305 type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
2306 pos: number
2307 line: number
2308 col: number
2309 },
2310 ) => boolean)
2311 ecma?: ECMA
2312 ie8?: boolean
2313 keep_numbers?: boolean
2314 indent_level?: number
2315 indent_start?: number
2316 inline_script?: boolean
2317 keep_quoted_props?: boolean
2318 max_line_len?: number | false
2319 preamble?: string
2320 preserve_annotations?: boolean
2321 quote_keys?: boolean
2322 quote_style?: OutputQuoteStyle
2323 safari10?: boolean
2324 semicolons?: boolean
2325 shebang?: boolean
2326 shorthand?: boolean
2327 source_map?: SourceMapOptions
2328 webkit?: boolean
2329 width?: number
2330 wrap_iife?: boolean
2331 wrap_func_args?: boolean
2332 }
2333
2334 export enum OutputQuoteStyle {
2335 PreferDouble = 0,
2336 AlwaysSingle = 1,
2337 AlwaysDouble = 2,
2338 AlwaysOriginal = 3,
2339 }
2340
2341 export interface MinifyOptions {
2342 compress?: boolean | CompressOptions
2343 ecma?: ECMA
2344 enclose?: boolean | string
2345 ie8?: boolean
2346 keep_classnames?: boolean | RegExp
2347 keep_fnames?: boolean | RegExp
2348 mangle?: boolean | MangleOptions
2349 module?: boolean
2350 nameCache?: object
2351 format?: FormatOptions
2352 /** @deprecated */
2353 output?: FormatOptions
2354 parse?: ParseOptions
2355 safari10?: boolean
2356 sourceMap?: boolean | SourceMapOptions
2357 toplevel?: boolean
2358 }
2359
2360 export interface MinifyOutput {
2361 code?: string
2362 map?: object | string
2363 decoded_map?: object | null
2364 }
2365
2366 export interface SourceMapOptions {
2367 /** Source map object, 'inline' or source map file content */
2368 content?: object | string
2369 includeSources?: boolean
2370 filename?: string
2371 root?: string
2372 asObject?: boolean
2373 url?: string | 'inline'
2374 }
2375}
2376
2377interface TerserOptions extends Terser.MinifyOptions {
2378 /**
2379 * Vite-specific option to specify the max number of workers to spawn
2380 * when minifying files with terser.
2381 *
2382 * @default number of CPUs minus 1
2383 */
2384 maxWorkers?: number;
2385}
2386
2387interface EnvironmentResolveOptions {
2388 /**
2389 * @default ['browser', 'module', 'jsnext:main', 'jsnext']
2390 */
2391 mainFields?: string[];
2392 conditions?: string[];
2393 externalConditions?: string[];
2394 /**
2395 * @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
2396 */
2397 extensions?: string[];
2398 dedupe?: string[];
2399 /**
2400 * Prevent listed dependencies from being externalized and will get bundled in build.
2401 * Only works in server environments for now. Previously this was `ssr.noExternal`.
2402 * @experimental
2403 */
2404 noExternal?: string | RegExp | (string | RegExp)[] | true;
2405 /**
2406 * Externalize the given dependencies and their transitive dependencies.
2407 * Only works in server environments for now. Previously this was `ssr.external`.
2408 * @experimental
2409 */
2410 external?: string[] | true;
2411}
2412interface ResolveOptions extends EnvironmentResolveOptions {
2413 /**
2414 * @default false
2415 */
2416 preserveSymlinks?: boolean;
2417}
2418interface ResolvePluginOptions {
2419 root: string;
2420 isBuild: boolean;
2421 isProduction: boolean;
2422 packageCache?: PackageCache;
2423 /**
2424 * src code mode also attempts the following:
2425 * - resolving /xxx as URLs
2426 * - resolving bare imports from optimized deps
2427 */
2428 asSrc?: boolean;
2429 tryIndex?: boolean;
2430 tryPrefix?: string;
2431 preferRelative?: boolean;
2432 isRequire?: boolean;
2433 isFromTsImporter?: boolean;
2434 scan?: boolean;
2435 /**
2436 * @deprecated environment.config are used instead
2437 */
2438 ssrConfig?: SSROptions;
2439}
2440interface InternalResolveOptions extends Required<Omit<ResolveOptions, 'enableBuiltinNoExternalCheck'>>, ResolvePluginOptions {
2441}
2442
2443/** Cache for package.json resolution and package.json contents */
2444type PackageCache = Map<string, PackageData>;
2445interface PackageData {
2446 dir: string;
2447 hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
2448 setResolvedCache: (key: string, entry: string, options: InternalResolveOptions) => void;
2449 getResolvedCache: (key: string, options: InternalResolveOptions) => string | undefined;
2450 data: {
2451 [field: string]: any;
2452 name: string;
2453 type: string;
2454 version: string;
2455 main: string;
2456 module: string;
2457 browser: string | Record<string, string | false>;
2458 exports: string | Record<string, any> | string[];
2459 imports: Record<string, any>;
2460 dependencies: Record<string, string>;
2461 };
2462}
2463
2464interface BuildEnvironmentOptions {
2465 /**
2466 * Compatibility transform target. The transform is performed with esbuild
2467 * and the lowest supported target is es2015. Note this only handles
2468 * syntax transformation and does not cover polyfills
2469 *
2470 * Default: 'modules' - transpile targeting browsers that natively support
2471 * dynamic es module imports and `import.meta`
2472 * (Chrome 87+, Firefox 78+, Safari 14+, Edge 88+).
2473 *
2474 * Another special value is 'esnext' - which only performs minimal transpiling
2475 * (for minification compat).
2476 *
2477 * For custom targets, see https://esbuild.github.io/api/#target and
2478 * https://esbuild.github.io/content-types/#javascript for more details.
2479 * @default 'modules'
2480 */
2481 target?: 'modules' | esbuild_TransformOptions['target'] | false;
2482 /**
2483 * whether to inject module preload polyfill.
2484 * Note: does not apply to library mode.
2485 * @default true
2486 * @deprecated use `modulePreload.polyfill` instead
2487 */
2488 polyfillModulePreload?: boolean;
2489 /**
2490 * Configure module preload
2491 * Note: does not apply to library mode.
2492 * @default true
2493 */
2494 modulePreload?: boolean | ModulePreloadOptions;
2495 /**
2496 * Directory relative from `root` where build output will be placed. If the
2497 * directory exists, it will be removed before the build.
2498 * @default 'dist'
2499 */
2500 outDir?: string;
2501 /**
2502 * Directory relative from `outDir` where the built js/css/image assets will
2503 * be placed.
2504 * @default 'assets'
2505 */
2506 assetsDir?: string;
2507 /**
2508 * Static asset files smaller than this number (in bytes) will be inlined as
2509 * base64 strings. If a callback is passed, a boolean can be returned to opt-in
2510 * or opt-out of inlining. If nothing is returned the default logic applies.
2511 *
2512 * Default limit is `4096` (4 KiB). Set to `0` to disable.
2513 * @default 4096
2514 */
2515 assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
2516 /**
2517 * Whether to code-split CSS. When enabled, CSS in async chunks will be
2518 * inlined as strings in the chunk and inserted via dynamically created
2519 * style tags when the chunk is loaded.
2520 * @default true
2521 */
2522 cssCodeSplit?: boolean;
2523 /**
2524 * An optional separate target for CSS minification.
2525 * As esbuild only supports configuring targets to mainstream
2526 * browsers, users may need this option when they are targeting
2527 * a niche browser that comes with most modern JavaScript features
2528 * but has poor CSS support, e.g. Android WeChat WebView, which
2529 * doesn't support the #RGBA syntax.
2530 * @default target
2531 */
2532 cssTarget?: esbuild_TransformOptions['target'] | false;
2533 /**
2534 * Override CSS minification specifically instead of defaulting to `build.minify`,
2535 * so you can configure minification for JS and CSS separately.
2536 * @default 'esbuild'
2537 */
2538 cssMinify?: boolean | 'esbuild' | 'lightningcss';
2539 /**
2540 * If `true`, a separate sourcemap file will be created. If 'inline', the
2541 * sourcemap will be appended to the resulting output file as data URI.
2542 * 'hidden' works like `true` except that the corresponding sourcemap
2543 * comments in the bundled files are suppressed.
2544 * @default false
2545 */
2546 sourcemap?: boolean | 'inline' | 'hidden';
2547 /**
2548 * Set to `false` to disable minification, or specify the minifier to use.
2549 * Available options are 'terser' or 'esbuild'.
2550 * @default 'esbuild'
2551 */
2552 minify?: boolean | 'terser' | 'esbuild';
2553 /**
2554 * Options for terser
2555 * https://terser.org/docs/api-reference#minify-options
2556 *
2557 * In addition, you can also pass a `maxWorkers: number` option to specify the
2558 * max number of workers to spawn. Defaults to the number of CPUs minus 1.
2559 */
2560 terserOptions?: TerserOptions;
2561 /**
2562 * Will be merged with internal rollup options.
2563 * https://rollupjs.org/configuration-options/
2564 */
2565 rollupOptions?: RollupOptions;
2566 /**
2567 * Options to pass on to `@rollup/plugin-commonjs`
2568 */
2569 commonjsOptions?: RollupCommonJSOptions;
2570 /**
2571 * Options to pass on to `@rollup/plugin-dynamic-import-vars`
2572 */
2573 dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
2574 /**
2575 * Whether to write bundle to disk
2576 * @default true
2577 */
2578 write?: boolean;
2579 /**
2580 * Empty outDir on write.
2581 * @default true when outDir is a sub directory of project root
2582 */
2583 emptyOutDir?: boolean | null;
2584 /**
2585 * Copy the public directory to outDir on write.
2586 * @default true
2587 */
2588 copyPublicDir?: boolean;
2589 /**
2590 * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
2591 * to their hashed versions. Useful when you want to generate your own HTML
2592 * instead of using the one generated by Vite.
2593 *
2594 * Example:
2595 *
2596 * ```json
2597 * {
2598 * "main.js": {
2599 * "file": "main.68fe3fad.js",
2600 * "css": "main.e6b63442.css",
2601 * "imports": [...],
2602 * "dynamicImports": [...]
2603 * }
2604 * }
2605 * ```
2606 * @default false
2607 */
2608 manifest?: boolean | string;
2609 /**
2610 * Build in library mode. The value should be the global name of the lib in
2611 * UMD mode. This will produce esm + cjs + umd bundle formats with default
2612 * configurations that are suitable for distributing libraries.
2613 * @default false
2614 */
2615 lib?: LibraryOptions | false;
2616 /**
2617 * Produce SSR oriented build. Note this requires specifying SSR entry via
2618 * `rollupOptions.input`.
2619 * @default false
2620 */
2621 ssr?: boolean | string;
2622 /**
2623 * Generate SSR manifest for determining style links and asset preload
2624 * directives in production.
2625 * @default false
2626 */
2627 ssrManifest?: boolean | string;
2628 /**
2629 * Emit assets during SSR.
2630 * @default false
2631 */
2632 ssrEmitAssets?: boolean;
2633 /**
2634 * Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
2635 * By default, it is true for the client and false for other environments.
2636 */
2637 emitAssets?: boolean;
2638 /**
2639 * Set to false to disable reporting compressed chunk sizes.
2640 * Can slightly improve build speed.
2641 * @default true
2642 */
2643 reportCompressedSize?: boolean;
2644 /**
2645 * Adjust chunk size warning limit (in kB).
2646 * @default 500
2647 */
2648 chunkSizeWarningLimit?: number;
2649 /**
2650 * Rollup watch options
2651 * https://rollupjs.org/configuration-options/#watch
2652 * @default null
2653 */
2654 watch?: WatcherOptions | null;
2655 /**
2656 * create the Build Environment instance
2657 */
2658 createEnvironment?: (name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
2659}
2660type BuildOptions = BuildEnvironmentOptions;
2661interface LibraryOptions {
2662 /**
2663 * Path of library entry
2664 */
2665 entry: InputOption;
2666 /**
2667 * The name of the exposed global variable. Required when the `formats` option includes
2668 * `umd` or `iife`
2669 */
2670 name?: string;
2671 /**
2672 * Output bundle formats
2673 * @default ['es', 'umd']
2674 */
2675 formats?: LibraryFormats[];
2676 /**
2677 * The name of the package file output. The default file name is the name option
2678 * of the project package.json. It can also be defined as a function taking the
2679 * format as an argument.
2680 */
2681 fileName?: string | ((format: ModuleFormat, entryName: string) => string);
2682 /**
2683 * The name of the CSS file output if the library imports CSS. Defaults to the
2684 * same value as `build.lib.fileName` if it's set a string, otherwise it falls
2685 * back to the name option of the project package.json.
2686 */
2687 cssFileName?: string;
2688}
2689type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system';
2690interface ModulePreloadOptions {
2691 /**
2692 * Whether to inject a module preload polyfill.
2693 * Note: does not apply to library mode.
2694 * @default true
2695 */
2696 polyfill?: boolean;
2697 /**
2698 * Resolve the list of dependencies to preload for a given dynamic import
2699 * @experimental
2700 */
2701 resolveDependencies?: ResolveModulePreloadDependenciesFn;
2702}
2703interface ResolvedModulePreloadOptions {
2704 polyfill: boolean;
2705 resolveDependencies?: ResolveModulePreloadDependenciesFn;
2706}
2707type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
2708 hostId: string;
2709 hostType: 'html' | 'js';
2710}) => string[];
2711interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {
2712 modulePreload: false | ResolvedModulePreloadOptions;
2713}
2714interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
2715 modulePreload: false | ResolvedModulePreloadOptions;
2716}
2717/**
2718 * Bundles a single environment for production.
2719 * Returns a Promise containing the build result.
2720 */
2721declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2722type RenderBuiltAssetUrl = (filename: string, type: {
2723 type: 'asset' | 'public';
2724 hostId: string;
2725 hostType: 'js' | 'css' | 'html';
2726 ssr: boolean;
2727}) => string | {
2728 relative?: boolean;
2729 runtime?: string;
2730} | undefined;
2731declare class BuildEnvironment extends BaseEnvironment {
2732 mode: "build";
2733 constructor(name: string, config: ResolvedConfig, setup?: {
2734 options?: EnvironmentOptions;
2735 });
2736 init(): Promise<void>;
2737}
2738interface ViteBuilder {
2739 environments: Record<string, BuildEnvironment>;
2740 config: ResolvedConfig;
2741 buildApp(): Promise<void>;
2742 build(environment: BuildEnvironment): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2743}
2744interface BuilderOptions {
2745 /**
2746 * Whether to share the config instance among environments to align with the behavior of dev server.
2747 *
2748 * @default false
2749 * @experimental
2750 */
2751 sharedConfigBuild?: boolean;
2752 /**
2753 * Whether to share the plugin instances among environments to align with the behavior of dev server.
2754 *
2755 * @default false
2756 * @experimental
2757 */
2758 sharedPlugins?: boolean;
2759 buildApp?: (builder: ViteBuilder) => Promise<void>;
2760}
2761type ResolvedBuilderOptions = Required<BuilderOptions>;
2762/**
2763 * Creates a ViteBuilder to orchestrate building multiple environments.
2764 * @experimental
2765 */
2766declare function createBuilder(inlineConfig?: InlineConfig, useLegacyBuilder?: null | boolean): Promise<ViteBuilder>;
2767
2768type Environment = DevEnvironment | BuildEnvironment | UnknownEnvironment;
2769/**
2770 * Creates a function that hides the complexities of a WeakMap with an initial value
2771 * to implement object metadata. Used by plugins to implement cross hooks per
2772 * environment metadata
2773 *
2774 * @experimental
2775 */
2776declare function perEnvironmentState<State>(initial: (environment: Environment) => State): (context: PluginContext) => State;
2777
2778type SkipInformation = {
2779 id: string;
2780 importer: string | undefined;
2781 plugin: Plugin;
2782 called?: boolean;
2783};
2784declare class EnvironmentPluginContainer {
2785 environment: Environment;
2786 plugins: Plugin[];
2787 watcher?: FSWatcher | undefined;
2788 private _pluginContextMap;
2789 private _resolvedRollupOptions?;
2790 private _processesing;
2791 private _seenResolves;
2792 private _moduleNodeToLoadAddedImports;
2793 getSortedPluginHooks: PluginHookUtils['getSortedPluginHooks'];
2794 getSortedPlugins: PluginHookUtils['getSortedPlugins'];
2795 moduleGraph: EnvironmentModuleGraph | undefined;
2796 watchFiles: Set<string>;
2797 minimalContext: MinimalPluginContext;
2798 private _started;
2799 private _buildStartPromise;
2800 private _closed;
2801 private _updateModuleLoadAddedImports;
2802 private _getAddedImports;
2803 getModuleInfo(id: string): ModuleInfo | null;
2804 private handleHookPromise;
2805 get options(): InputOptions;
2806 resolveRollupOptions(): Promise<InputOptions>;
2807 private _getPluginContext;
2808 private hookParallel;
2809 buildStart(_options?: InputOptions): Promise<void>;
2810 resolveId(rawId: string, importer?: string | undefined, options?: {
2811 attributes?: Record<string, string>;
2812 custom?: CustomPluginOptions;
2813 /** @deprecated use `skipCalls` instead */
2814 skip?: Set<Plugin>;
2815 skipCalls?: readonly SkipInformation[];
2816 isEntry?: boolean;
2817 }): Promise<PartialResolvedId | null>;
2818 load(id: string): Promise<LoadResult | null>;
2819 transform(code: string, id: string, options?: {
2820 inMap?: SourceDescription['map'];
2821 }): Promise<{
2822 code: string;
2823 map: SourceMap | {
2824 mappings: '';
2825 } | null;
2826 }>;
2827 watchChange(id: string, change: {
2828 event: 'create' | 'update' | 'delete';
2829 }): Promise<void>;
2830 close(): Promise<void>;
2831}
2832declare class PluginContainer {
2833 private environments;
2834 constructor(environments: Record<string, Environment>);
2835 private _getEnvironment;
2836 private _getPluginContainer;
2837 getModuleInfo(id: string): ModuleInfo | null;
2838 get options(): InputOptions;
2839 buildStart(_options?: InputOptions): Promise<void>;
2840 watchChange(id: string, change: {
2841 event: 'create' | 'update' | 'delete';
2842 }): Promise<void>;
2843 resolveId(rawId: string, importer?: string, options?: {
2844 attributes?: Record<string, string>;
2845 custom?: CustomPluginOptions;
2846 /** @deprecated use `skipCalls` instead */
2847 skip?: Set<Plugin>;
2848 skipCalls?: readonly SkipInformation[];
2849 ssr?: boolean;
2850 isEntry?: boolean;
2851 }): Promise<PartialResolvedId | null>;
2852 load(id: string, options?: {
2853 ssr?: boolean;
2854 }): Promise<LoadResult | null>;
2855 transform(code: string, id: string, options?: {
2856 ssr?: boolean;
2857 environment?: Environment;
2858 inMap?: SourceDescription['map'];
2859 }): Promise<{
2860 code: string;
2861 map: SourceMap | {
2862 mappings: '';
2863 } | null;
2864 }>;
2865 close(): Promise<void>;
2866}
2867
2868interface ServerOptions extends CommonServerOptions {
2869 /**
2870 * Configure HMR-specific options (port, host, path & protocol)
2871 */
2872 hmr?: HmrOptions | boolean;
2873 /**
2874 * Do not start the websocket connection.
2875 * @experimental
2876 */
2877 ws?: false;
2878 /**
2879 * Warm-up files to transform and cache the results in advance. This improves the
2880 * initial page load during server starts and prevents transform waterfalls.
2881 */
2882 warmup?: {
2883 /**
2884 * The files to be transformed and used on the client-side. Supports glob patterns.
2885 */
2886 clientFiles?: string[];
2887 /**
2888 * The files to be transformed and used in SSR. Supports glob patterns.
2889 */
2890 ssrFiles?: string[];
2891 };
2892 /**
2893 * chokidar watch options or null to disable FS watching
2894 * https://github.com/paulmillr/chokidar/tree/3.6.0#api
2895 */
2896 watch?: WatchOptions | null;
2897 /**
2898 * Create Vite dev server to be used as a middleware in an existing server
2899 * @default false
2900 */
2901 middlewareMode?: boolean | {
2902 /**
2903 * Parent server instance to attach to
2904 *
2905 * This is needed to proxy WebSocket connections to the parent server.
2906 */
2907 server: HttpServer;
2908 };
2909 /**
2910 * Options for files served via '/\@fs/'.
2911 */
2912 fs?: FileSystemServeOptions;
2913 /**
2914 * Origin for the generated asset URLs.
2915 *
2916 * @example `http://127.0.0.1:8080`
2917 */
2918 origin?: string;
2919 /**
2920 * Pre-transform known direct imports
2921 * @default true
2922 */
2923 preTransformRequests?: boolean;
2924 /**
2925 * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
2926 * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
2927 *
2928 * By default, it excludes all paths containing `node_modules`. You can pass `false` to
2929 * disable this behavior, or, for full control, a function that takes the source path and
2930 * sourcemap path and returns whether to ignore the source path.
2931 */
2932 sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
2933 /**
2934 * Backward compatibility. The buildStart and buildEnd hooks were called only once for all
2935 * environments. This option enables per-environment buildStart and buildEnd hooks.
2936 * @default false
2937 * @experimental
2938 */
2939 perEnvironmentStartEndDuringDev?: boolean;
2940 /**
2941 * Run HMR tasks, by default the HMR propagation is done in parallel for all environments
2942 * @experimental
2943 */
2944 hotUpdateEnvironments?: (server: ViteDevServer, hmr: (environment: DevEnvironment) => Promise<void>) => Promise<void>;
2945}
2946interface ResolvedServerOptions extends Omit<RequiredExceptFor<ServerOptions, 'host' | 'https' | 'proxy' | 'hmr' | 'ws' | 'watch' | 'origin' | 'hotUpdateEnvironments'>, 'fs' | 'middlewareMode' | 'sourcemapIgnoreList'> {
2947 fs: Required<FileSystemServeOptions>;
2948 middlewareMode: NonNullable<ServerOptions['middlewareMode']>;
2949 sourcemapIgnoreList: Exclude<ServerOptions['sourcemapIgnoreList'], false | undefined>;
2950}
2951interface FileSystemServeOptions {
2952 /**
2953 * Strictly restrict file accessing outside of allowing paths.
2954 *
2955 * Set to `false` to disable the warning
2956 *
2957 * @default true
2958 */
2959 strict?: boolean;
2960 /**
2961 * Restrict accessing files outside the allowed directories.
2962 *
2963 * Accepts absolute path or a path relative to project root.
2964 * Will try to search up for workspace root by default.
2965 */
2966 allow?: string[];
2967 /**
2968 * Restrict accessing files that matches the patterns.
2969 *
2970 * This will have higher priority than `allow`.
2971 * picomatch patterns are supported.
2972 *
2973 * @default ['.env', '.env.*', '*.{crt,pem}', '**\/.git/**']
2974 */
2975 deny?: string[];
2976}
2977type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
2978type HttpServer = http.Server | Http2SecureServer;
2979interface ViteDevServer {
2980 /**
2981 * The resolved vite config object
2982 */
2983 config: ResolvedConfig;
2984 /**
2985 * A connect app instance.
2986 * - Can be used to attach custom middlewares to the dev server.
2987 * - Can also be used as the handler function of a custom http server
2988 * or as a middleware in any connect-style Node.js frameworks
2989 *
2990 * https://github.com/senchalabs/connect#use-middleware
2991 */
2992 middlewares: Connect.Server;
2993 /**
2994 * native Node http server instance
2995 * will be null in middleware mode
2996 */
2997 httpServer: HttpServer | null;
2998 /**
2999 * Chokidar watcher instance. If `config.server.watch` is set to `null`,
3000 * it will not watch any files and calling `add` or `unwatch` will have no effect.
3001 * https://github.com/paulmillr/chokidar/tree/3.6.0#api
3002 */
3003 watcher: FSWatcher;
3004 /**
3005 * web socket server with `send(payload)` method
3006 */
3007 ws: WebSocketServer;
3008 /**
3009 * HMR broadcaster that can be used to send custom HMR messages to the client
3010 *
3011 * Always sends a message to at least a WebSocket client. Any third party can
3012 * add a channel to the broadcaster to process messages
3013 */
3014 hot: HotBroadcaster;
3015 /**
3016 * Rollup plugin container that can run plugin hooks on a given file
3017 */
3018 pluginContainer: PluginContainer;
3019 /**
3020 * Module execution environments attached to the Vite server.
3021 */
3022 environments: Record<'client' | 'ssr' | (string & {}), DevEnvironment>;
3023 /**
3024 * Module graph that tracks the import relationships, url to file mapping
3025 * and hmr state.
3026 */
3027 moduleGraph: ModuleGraph;
3028 /**
3029 * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
3030 * in middleware mode or if the server is not listening on any port.
3031 */
3032 resolvedUrls: ResolvedServerUrls | null;
3033 /**
3034 * Programmatically resolve, load and transform a URL and get the result
3035 * without going through the http request pipeline.
3036 */
3037 transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
3038 /**
3039 * Same as `transformRequest` but only warm up the URLs so the next request
3040 * will already be cached. The function will never throw as it handles and
3041 * reports errors internally.
3042 */
3043 warmupRequest(url: string, options?: TransformOptions): Promise<void>;
3044 /**
3045 * Apply vite built-in HTML transforms and any plugin HTML transforms.
3046 */
3047 transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
3048 /**
3049 * Transform module code into SSR format.
3050 */
3051 ssrTransform(code: string, inMap: SourceMap | {
3052 mappings: '';
3053 } | null, url: string, originalCode?: string): Promise<TransformResult | null>;
3054 /**
3055 * Load a given URL as an instantiated module for SSR.
3056 */
3057 ssrLoadModule(url: string, opts?: {
3058 fixStacktrace?: boolean;
3059 }): Promise<Record<string, any>>;
3060 /**
3061 * Returns a fixed version of the given stack
3062 */
3063 ssrRewriteStacktrace(stack: string): string;
3064 /**
3065 * Mutates the given SSR error by rewriting the stacktrace
3066 */
3067 ssrFixStacktrace(e: Error): void;
3068 /**
3069 * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
3070 * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
3071 */
3072 reloadModule(module: ModuleNode): Promise<void>;
3073 /**
3074 * Start the server.
3075 */
3076 listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
3077 /**
3078 * Stop the server.
3079 */
3080 close(): Promise<void>;
3081 /**
3082 * Print server urls
3083 */
3084 printUrls(): void;
3085 /**
3086 * Bind CLI shortcuts
3087 */
3088 bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void;
3089 /**
3090 * Restart the server.
3091 *
3092 * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
3093 */
3094 restart(forceOptimize?: boolean): Promise<void>;
3095 /**
3096 * Open browser
3097 */
3098 openBrowser(): void;
3099 /**
3100 * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
3101 * are processed. If called from a load or transform plugin hook, the id needs to be
3102 * passed as a parameter to avoid deadlocks. Calling this function after the first
3103 * static imports section of the module graph has been processed will resolve immediately.
3104 */
3105 waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
3106}
3107interface ResolvedServerUrls {
3108 local: string[];
3109 network: string[];
3110}
3111declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
3112
3113interface ESBuildOptions extends esbuild_TransformOptions {
3114 include?: string | RegExp | string[] | RegExp[];
3115 exclude?: string | RegExp | string[] | RegExp[];
3116 jsxInject?: string;
3117 /**
3118 * This option is not respected. Use `build.minify` instead.
3119 */
3120 minify?: never;
3121}
3122type ESBuildTransformResult = Omit<esbuild_TransformResult, 'map'> & {
3123 map: SourceMap;
3124};
3125declare function transformWithEsbuild(code: string, filename: string, options?: esbuild_TransformOptions, inMap?: object, config?: ResolvedConfig, watcher?: FSWatcher): Promise<ESBuildTransformResult>;
3126
3127interface JsonOptions {
3128 /**
3129 * Generate a named export for every property of the JSON object
3130 * @default true
3131 */
3132 namedExports?: boolean;
3133 /**
3134 * Generate performant output as JSON.parse("stringified").
3135 *
3136 * When set to 'auto', the data will be stringified only if the data is bigger than 10kB.
3137 * @default 'auto'
3138 */
3139 stringify?: boolean | 'auto';
3140}
3141
3142interface CSSOptions {
3143 /**
3144 * Using lightningcss is an experimental option to handle CSS modules,
3145 * assets and imports via Lightning CSS. It requires to install it as a
3146 * peer dependency. This is incompatible with the use of preprocessors.
3147 *
3148 * @default 'postcss'
3149 * @experimental
3150 */
3151 transformer?: 'postcss' | 'lightningcss';
3152 /**
3153 * https://github.com/css-modules/postcss-modules
3154 */
3155 modules?: CSSModulesOptions | false;
3156 /**
3157 * Options for preprocessors.
3158 *
3159 * In addition to options specific to each processors, Vite supports `additionalData` option.
3160 * The `additionalData` option can be used to inject extra code for each style content.
3161 */
3162 preprocessorOptions?: {
3163 scss?: SassPreprocessorOptions;
3164 sass?: SassPreprocessorOptions;
3165 less?: LessPreprocessorOptions;
3166 styl?: StylusPreprocessorOptions;
3167 stylus?: StylusPreprocessorOptions;
3168 };
3169 /**
3170 * If this option is set, preprocessors will run in workers when possible.
3171 * `true` means the number of CPUs minus 1.
3172 *
3173 * @default 0
3174 * @experimental
3175 */
3176 preprocessorMaxWorkers?: number | true;
3177 postcss?: string | (PostCSS.ProcessOptions & {
3178 plugins?: PostCSS.AcceptedPlugin[];
3179 });
3180 /**
3181 * Enables css sourcemaps during dev
3182 * @default false
3183 * @experimental
3184 */
3185 devSourcemap?: boolean;
3186 /**
3187 * @experimental
3188 */
3189 lightningcss?: LightningCSSOptions;
3190}
3191interface CSSModulesOptions {
3192 getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
3193 scopeBehaviour?: 'global' | 'local';
3194 globalModulePaths?: RegExp[];
3195 exportGlobals?: boolean;
3196 generateScopedName?: string | ((name: string, filename: string, css: string) => string);
3197 hashPrefix?: string;
3198 /**
3199 * default: undefined
3200 */
3201 localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | ((originalClassName: string, generatedClassName: string, inputFile: string) => string);
3202}
3203type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> & Required<Pick<CSSOptions, 'transformer'>> & {
3204 lightningcss?: LightningCSSOptions;
3205};
3206interface PreprocessCSSResult {
3207 code: string;
3208 map?: SourceMapInput;
3209 modules?: Record<string, string>;
3210 deps?: Set<string>;
3211}
3212/**
3213 * @experimental
3214 */
3215declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig): Promise<PreprocessCSSResult>;
3216declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): Promise<ExistingRawSourceMap>;
3217type PreprocessorAdditionalDataResult = string | {
3218 content: string;
3219 map?: ExistingRawSourceMap;
3220};
3221type PreprocessorAdditionalData = string | ((source: string, filename: string) => PreprocessorAdditionalDataResult | Promise<PreprocessorAdditionalDataResult>);
3222type SassPreprocessorOptions = {
3223 additionalData?: PreprocessorAdditionalData;
3224} & (({
3225 api: 'legacy';
3226} & SassLegacyPreprocessBaseOptions) | ({
3227 api?: 'modern' | 'modern-compiler';
3228} & SassModernPreprocessBaseOptions));
3229type LessPreprocessorOptions = {
3230 additionalData?: PreprocessorAdditionalData;
3231} & LessPreprocessorBaseOptions;
3232type StylusPreprocessorOptions = {
3233 additionalData?: PreprocessorAdditionalData;
3234} & StylusPreprocessorBaseOptions;
3235
3236interface HtmlTagDescriptor {
3237 tag: string;
3238 attrs?: Record<string, string | boolean | undefined>;
3239 children?: string | HtmlTagDescriptor[];
3240 /**
3241 * default: 'head-prepend'
3242 */
3243 injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend';
3244}
3245type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | {
3246 html: string;
3247 tags: HtmlTagDescriptor[];
3248};
3249interface IndexHtmlTransformContext {
3250 /**
3251 * public path when served
3252 */
3253 path: string;
3254 /**
3255 * filename on disk
3256 */
3257 filename: string;
3258 server?: ViteDevServer;
3259 bundle?: OutputBundle;
3260 chunk?: OutputChunk;
3261 originalUrl?: string;
3262}
3263type IndexHtmlTransformHook = (this: void, html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
3264type IndexHtmlTransform = IndexHtmlTransformHook | {
3265 order?: 'pre' | 'post' | null;
3266 /**
3267 * @deprecated renamed to `order`
3268 */
3269 enforce?: 'pre' | 'post';
3270 /**
3271 * @deprecated renamed to `handler`
3272 */
3273 transform: IndexHtmlTransformHook;
3274} | {
3275 order?: 'pre' | 'post' | null;
3276 /**
3277 * @deprecated renamed to `order`
3278 */
3279 enforce?: 'pre' | 'post';
3280 handler: IndexHtmlTransformHook;
3281};
3282
3283/**
3284 * Vite plugins extends the Rollup plugin interface with a few extra
3285 * vite-specific options. A valid vite plugin is also a valid Rollup plugin.
3286 * On the contrary, a Rollup plugin may or may NOT be a valid vite universal
3287 * plugin, since some Rollup features do not make sense in an unbundled
3288 * dev server context. That said, as long as a rollup plugin doesn't have strong
3289 * coupling between its bundle phase and output phase hooks then it should
3290 * just work (that means, most of them).
3291 *
3292 * By default, the plugins are run during both serve and build. When a plugin
3293 * is applied during serve, it will only run **non output plugin hooks** (see
3294 * rollup type definition of {@link rollup#PluginHooks}). You can think of the
3295 * dev server as only running `const bundle = rollup.rollup()` but never calling
3296 * `bundle.generate()`.
3297 *
3298 * A plugin that expects to have different behavior depending on serve/build can
3299 * export a factory function that receives the command being run via options.
3300 *
3301 * If a plugin should be applied only for server or build, a function format
3302 * config file can be used to conditional determine the plugins to use.
3303 *
3304 * The current environment can be accessed from the context for the all non-global
3305 * hooks (it is not available in config, configResolved, configureServer, etc).
3306 * It can be a dev, build, or scan environment.
3307 * Plugins can use this.environment.mode === 'dev' to guard for dev specific APIs.
3308 */
3309interface PluginContextExtension {
3310 /**
3311 * Vite-specific environment instance
3312 */
3313 environment: Environment;
3314}
3315interface HotUpdatePluginContext {
3316 environment: DevEnvironment;
3317}
3318interface PluginContext extends rollup.PluginContext, PluginContextExtension {
3319}
3320interface ResolveIdPluginContext extends rollup.PluginContext, PluginContextExtension {
3321}
3322interface TransformPluginContext extends rollup.TransformPluginContext, PluginContextExtension {
3323}
3324declare module 'rollup' {
3325 interface MinimalPluginContext extends PluginContextExtension {
3326 }
3327}
3328/**
3329 * There are two types of plugins in Vite. App plugins and environment plugins.
3330 * Environment Plugins are defined by a constructor function that will be called
3331 * once per each environment allowing users to have completely different plugins
3332 * for each of them. The constructor gets the resolved environment after the server
3333 * and builder has already been created simplifying config access and cache
3334 * management for for environment specific plugins.
3335 * Environment Plugins are closer to regular rollup plugins. They can't define
3336 * app level hooks (like config, configResolved, configureServer, etc).
3337 */
3338interface Plugin<A = any> extends rollup.Plugin<A> {
3339 /**
3340 * Perform custom handling of HMR updates.
3341 * The handler receives an options containing changed filename, timestamp, a
3342 * list of modules affected by the file change, and the dev server instance.
3343 *
3344 * - The hook can return a filtered list of modules to narrow down the update.
3345 * e.g. for a Vue SFC, we can narrow down the part to update by comparing
3346 * the descriptors.
3347 *
3348 * - The hook can also return an empty array and then perform custom updates
3349 * by sending a custom hmr payload via environment.hot.send().
3350 *
3351 * - If the hook doesn't return a value, the hmr update will be performed as
3352 * normal.
3353 */
3354 hotUpdate?: ObjectHook<(this: HotUpdatePluginContext, options: HotUpdateOptions) => Array<EnvironmentModuleNode> | void | Promise<Array<EnvironmentModuleNode> | void>>;
3355 /**
3356 * extend hooks with ssr flag
3357 */
3358 resolveId?: ObjectHook<(this: ResolveIdPluginContext, source: string, importer: string | undefined, options: {
3359 attributes: Record<string, string>;
3360 custom?: CustomPluginOptions;
3361 ssr?: boolean;
3362 isEntry: boolean;
3363 }) => Promise<ResolveIdResult> | ResolveIdResult>;
3364 load?: ObjectHook<(this: PluginContext, id: string, options?: {
3365 ssr?: boolean;
3366 }) => Promise<LoadResult> | LoadResult>;
3367 transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: {
3368 ssr?: boolean;
3369 }) => Promise<rollup.TransformResult> | rollup.TransformResult>;
3370 /**
3371 * Opt-in this plugin into the shared plugins pipeline.
3372 * For backward-compatibility, plugins are re-recreated for each environment
3373 * during `vite build --app`
3374 * We have an opt-in per plugin, and a general `builder.sharedPlugins`
3375 * In a future major, we'll flip the default to be shared by default
3376 * @experimental
3377 */
3378 sharedDuringBuild?: boolean;
3379 /**
3380 * Opt-in this plugin into per-environment buildStart and buildEnd during dev.
3381 * For backward-compatibility, the buildStart hook is called only once during
3382 * dev, for the client environment. Plugins can opt-in to be called
3383 * per-environment, aligning with the build hook behavior.
3384 * @experimental
3385 */
3386 perEnvironmentStartEndDuringDev?: boolean;
3387 /**
3388 * Enforce plugin invocation tier similar to webpack loaders. Hooks ordering
3389 * is still subject to the `order` property in the hook object.
3390 *
3391 * Plugin invocation order:
3392 * - alias resolution
3393 * - `enforce: 'pre'` plugins
3394 * - vite core plugins
3395 * - normal plugins
3396 * - vite build plugins
3397 * - `enforce: 'post'` plugins
3398 * - vite build post plugins
3399 */
3400 enforce?: 'pre' | 'post';
3401 /**
3402 * Apply the plugin only for serve or build, or on certain conditions.
3403 */
3404 apply?: 'serve' | 'build' | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
3405 /**
3406 * Define environments where this plugin should be active
3407 * By default, the plugin is active in all environments
3408 * @experimental
3409 */
3410 applyToEnvironment?: (environment: PartialEnvironment) => boolean | Promise<boolean> | PluginOption;
3411 /**
3412 * Modify vite config before it's resolved. The hook can either mutate the
3413 * passed-in config directly, or return a partial config object that will be
3414 * deeply merged into existing config.
3415 *
3416 * Note: User plugins are resolved before running this hook so injecting other
3417 * plugins inside the `config` hook will have no effect.
3418 */
3419 config?: ObjectHook<(this: void, config: UserConfig, env: ConfigEnv) => Omit<UserConfig, 'plugins'> | null | void | Promise<Omit<UserConfig, 'plugins'> | null | void>>;
3420 /**
3421 * Modify environment configs before it's resolved. The hook can either mutate the
3422 * passed-in environment config directly, or return a partial config object that will be
3423 * deeply merged into existing config.
3424 * This hook is called for each environment with a partially resolved environment config
3425 * that already accounts for the default environment config values set at the root level.
3426 * If plugins need to modify the config of a given environment, they should do it in this
3427 * hook instead of the config hook. Leaving the config hook only for modifying the root
3428 * default environment config.
3429 */
3430 configEnvironment?: ObjectHook<(this: void, name: string, config: EnvironmentOptions, env: ConfigEnv & {
3431 /**
3432 * Whether this environment is SSR environment and `ssr.target` is set to `'webworker'`.
3433 * Only intended to be used for backward compatibility.
3434 */
3435 isSsrTargetWebworker?: boolean;
3436 }) => EnvironmentOptions | null | void | Promise<EnvironmentOptions | null | void>>;
3437 /**
3438 * Use this hook to read and store the final resolved vite config.
3439 */
3440 configResolved?: ObjectHook<(this: void, config: ResolvedConfig) => void | Promise<void>>;
3441 /**
3442 * Configure the vite server. The hook receives the {@link ViteDevServer}
3443 * instance. This can also be used to store a reference to the server
3444 * for use in other hooks.
3445 *
3446 * The hooks will be called before internal middlewares are applied. A hook
3447 * can return a post hook that will be called after internal middlewares
3448 * are applied. Hook can be async functions and will be called in series.
3449 */
3450 configureServer?: ObjectHook<ServerHook>;
3451 /**
3452 * Configure the preview server. The hook receives the {@link PreviewServer}
3453 * instance. This can also be used to store a reference to the server
3454 * for use in other hooks.
3455 *
3456 * The hooks are called before other middlewares are applied. A hook can
3457 * return a post hook that will be called after other middlewares are
3458 * applied. Hooks can be async functions and will be called in series.
3459 */
3460 configurePreviewServer?: ObjectHook<PreviewServerHook>;
3461 /**
3462 * Transform index.html.
3463 * The hook receives the following arguments:
3464 *
3465 * - html: string
3466 * - ctx?: vite.ServerContext (only present during serve)
3467 * - bundle?: rollup.OutputBundle (only present during build)
3468 *
3469 * It can either return a transformed string, or a list of html tag
3470 * descriptors that will be injected into the `<head>` or `<body>`.
3471 *
3472 * By default the transform is applied **after** vite's internal html
3473 * transform. If you need to apply the transform before vite, use an object:
3474 * `{ order: 'pre', handler: hook }`
3475 */
3476 transformIndexHtml?: IndexHtmlTransform;
3477 /**
3478 * Perform custom handling of HMR updates.
3479 * The handler receives a context containing changed filename, timestamp, a
3480 * list of modules affected by the file change, and the dev server instance.
3481 *
3482 * - The hook can return a filtered list of modules to narrow down the update.
3483 * e.g. for a Vue SFC, we can narrow down the part to update by comparing
3484 * the descriptors.
3485 *
3486 * - The hook can also return an empty array and then perform custom updates
3487 * by sending a custom hmr payload via server.ws.send().
3488 *
3489 * - If the hook doesn't return a value, the hmr update will be performed as
3490 * normal.
3491 */
3492 handleHotUpdate?: ObjectHook<(this: void, ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>>;
3493}
3494type HookHandler<T> = T extends ObjectHook<infer H> ? H : T;
3495type PluginWithRequiredHook<K extends keyof Plugin> = Plugin & {
3496 [P in K]: NonNullable<Plugin[P]>;
3497};
3498type Thenable<T> = T | Promise<T>;
3499type FalsyPlugin = false | null | undefined;
3500type PluginOption = Thenable<Plugin | FalsyPlugin | PluginOption[]>;
3501/**
3502 * @experimental
3503 */
3504declare function perEnvironmentPlugin(name: string, applyToEnvironment: (environment: PartialEnvironment) => boolean | Promise<boolean> | PluginOption): Plugin;
3505
3506type SSRTarget = 'node' | 'webworker';
3507type SsrDepOptimizationConfig = DepOptimizationConfig;
3508interface SSROptions {
3509 noExternal?: string | RegExp | (string | RegExp)[] | true;
3510 external?: string[] | true;
3511 /**
3512 * Define the target for the ssr build. The browser field in package.json
3513 * is ignored for node but used if webworker is the target
3514 * This option will be removed in a future major version
3515 * @default 'node'
3516 */
3517 target?: SSRTarget;
3518 /**
3519 * Control over which dependencies are optimized during SSR and esbuild options
3520 * During build:
3521 * no external CJS dependencies are optimized by default
3522 * During dev:
3523 * explicit no external CJS dependencies are optimized by default
3524 * @experimental
3525 */
3526 optimizeDeps?: SsrDepOptimizationConfig;
3527 resolve?: {
3528 /**
3529 * Conditions that are used in the plugin pipeline. The default value is the root config's `resolve.conditions`.
3530 *
3531 * Use this to override the default ssr conditions for the ssr build.
3532 *
3533 * @default rootConfig.resolve.conditions
3534 */
3535 conditions?: string[];
3536 /**
3537 * Conditions that are used during ssr import (including `ssrLoadModule`) of externalized dependencies.
3538 *
3539 * @default []
3540 */
3541 externalConditions?: string[];
3542 mainFields?: string[];
3543 };
3544}
3545interface ResolvedSSROptions extends SSROptions {
3546 target: SSRTarget;
3547 optimizeDeps: SsrDepOptimizationConfig;
3548}
3549
3550interface ConfigEnv {
3551 /**
3552 * 'serve': during dev (`vite` command)
3553 * 'build': when building for production (`vite build` command)
3554 */
3555 command: 'build' | 'serve';
3556 mode: string;
3557 isSsrBuild?: boolean;
3558 isPreview?: boolean;
3559}
3560/**
3561 * spa: include SPA fallback middleware and configure sirv with `single: true` in preview
3562 *
3563 * mpa: only include non-SPA HTML middlewares
3564 *
3565 * custom: don't include HTML middlewares
3566 */
3567type AppType = 'spa' | 'mpa' | 'custom';
3568type UserConfigFnObject = (env: ConfigEnv) => UserConfig;
3569type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>;
3570type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
3571type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFnObject | UserConfigFnPromise | UserConfigFn;
3572/**
3573 * Type helper to make it easier to use vite.config.ts
3574 * accepts a direct {@link UserConfig} object, or a function that returns it.
3575 * The function receives a {@link ConfigEnv} object.
3576 */
3577declare function defineConfig(config: UserConfig): UserConfig;
3578declare function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;
3579declare function defineConfig(config: UserConfigFnObject): UserConfigFnObject;
3580declare function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise;
3581declare function defineConfig(config: UserConfigFn): UserConfigFn;
3582declare function defineConfig(config: UserConfigExport): UserConfigExport;
3583interface CreateDevEnvironmentContext {
3584 ws: WebSocketServer;
3585}
3586interface DevEnvironmentOptions {
3587 /**
3588 * Files to be pre-transformed. Supports glob patterns.
3589 */
3590 warmup?: string[];
3591 /**
3592 * Pre-transform known direct imports
3593 * defaults to true for the client environment, false for the rest
3594 */
3595 preTransformRequests?: boolean;
3596 /**
3597 * Enables sourcemaps during dev
3598 * @default { js: true }
3599 * @experimental
3600 */
3601 sourcemap?: boolean | {
3602 js?: boolean;
3603 css?: boolean;
3604 };
3605 /**
3606 * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
3607 * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
3608 *
3609 * By default, it excludes all paths containing `node_modules`. You can pass `false` to
3610 * disable this behavior, or, for full control, a function that takes the source path and
3611 * sourcemap path and returns whether to ignore the source path.
3612 */
3613 sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
3614 /**
3615 * create the Dev Environment instance
3616 */
3617 createEnvironment?: (name: string, config: ResolvedConfig, context: CreateDevEnvironmentContext) => Promise<DevEnvironment> | DevEnvironment;
3618 /**
3619 * For environments that support a full-reload, like the client, we can short-circuit when
3620 * restarting the server throwing early to stop processing current files. We avoided this for
3621 * SSR requests. Maybe this is no longer needed.
3622 * @experimental
3623 */
3624 recoverable?: boolean;
3625 /**
3626 * For environments associated with a module runner.
3627 * By default it is true for the client environment and false for non-client environments.
3628 * This option can also be used instead of the removed config.experimental.skipSsrTransform.
3629 */
3630 moduleRunnerTransform?: boolean;
3631}
3632type ResolvedDevEnvironmentOptions = Omit<Required<DevEnvironmentOptions>, 'sourcemapIgnoreList'> & {
3633 sourcemapIgnoreList: Exclude<DevEnvironmentOptions['sourcemapIgnoreList'], false | undefined>;
3634};
3635type AllResolveOptions = ResolveOptions & {
3636 alias?: AliasOptions;
3637};
3638interface SharedEnvironmentOptions {
3639 /**
3640 * Define global variable replacements.
3641 * Entries will be defined on `window` during dev and replaced during build.
3642 */
3643 define?: Record<string, any>;
3644 /**
3645 * Configure resolver
3646 */
3647 resolve?: EnvironmentResolveOptions;
3648 /**
3649 * Define if this environment is used for Server Side Rendering
3650 * @default 'server' if it isn't the client environment
3651 */
3652 consumer?: 'client' | 'server';
3653 /**
3654 * If true, `process.env` referenced in code will be preserved as-is and evaluated in runtime.
3655 * Otherwise, it is statically replaced as an empty object.
3656 */
3657 keepProcessEnv?: boolean;
3658 /**
3659 * Optimize deps config
3660 */
3661 optimizeDeps?: DepOptimizationOptions;
3662}
3663interface EnvironmentOptions extends SharedEnvironmentOptions {
3664 /**
3665 * Dev specific options
3666 */
3667 dev?: DevEnvironmentOptions;
3668 /**
3669 * Build specific options
3670 */
3671 build?: BuildEnvironmentOptions;
3672}
3673type ResolvedResolveOptions = Required<ResolveOptions>;
3674type ResolvedEnvironmentOptions = {
3675 define?: Record<string, any>;
3676 resolve: ResolvedResolveOptions;
3677 consumer: 'client' | 'server';
3678 keepProcessEnv?: boolean;
3679 optimizeDeps: DepOptimizationOptions;
3680 dev: ResolvedDevEnvironmentOptions;
3681 build: ResolvedBuildEnvironmentOptions;
3682};
3683type DefaultEnvironmentOptions = Omit<EnvironmentOptions, 'consumer' | 'resolve'> & {
3684 resolve?: AllResolveOptions;
3685};
3686interface UserConfig extends DefaultEnvironmentOptions {
3687 /**
3688 * Project root directory. Can be an absolute path, or a path relative from
3689 * the location of the config file itself.
3690 * @default process.cwd()
3691 */
3692 root?: string;
3693 /**
3694 * Base public path when served in development or production.
3695 * @default '/'
3696 */
3697 base?: string;
3698 /**
3699 * Directory to serve as plain static assets. Files in this directory are
3700 * served and copied to build dist dir as-is without transform. The value
3701 * can be either an absolute file system path or a path relative to project root.
3702 *
3703 * Set to `false` or an empty string to disable copied static assets to build dist dir.
3704 * @default 'public'
3705 */
3706 publicDir?: string | false;
3707 /**
3708 * Directory to save cache files. Files in this directory are pre-bundled
3709 * deps or some other cache files that generated by vite, which can improve
3710 * the performance. You can use `--force` flag or manually delete the directory
3711 * to regenerate the cache files. The value can be either an absolute file
3712 * system path or a path relative to project root.
3713 * Default to `.vite` when no `package.json` is detected.
3714 * @default 'node_modules/.vite'
3715 */
3716 cacheDir?: string;
3717 /**
3718 * Explicitly set a mode to run in. This will override the default mode for
3719 * each command, and can be overridden by the command line --mode option.
3720 */
3721 mode?: string;
3722 /**
3723 * Array of vite plugins to use.
3724 */
3725 plugins?: PluginOption[];
3726 /**
3727 * HTML related options
3728 */
3729 html?: HTMLOptions;
3730 /**
3731 * CSS related options (preprocessors and CSS modules)
3732 */
3733 css?: CSSOptions;
3734 /**
3735 * JSON loading options
3736 */
3737 json?: JsonOptions;
3738 /**
3739 * Transform options to pass to esbuild.
3740 * Or set to `false` to disable esbuild.
3741 */
3742 esbuild?: ESBuildOptions | false;
3743 /**
3744 * Specify additional picomatch patterns to be treated as static assets.
3745 */
3746 assetsInclude?: string | RegExp | (string | RegExp)[];
3747 /**
3748 * Builder specific options
3749 * @experimental
3750 */
3751 builder?: BuilderOptions;
3752 /**
3753 * Server specific options, e.g. host, port, https...
3754 */
3755 server?: ServerOptions;
3756 /**
3757 * Preview specific options, e.g. host, port, https...
3758 */
3759 preview?: PreviewOptions;
3760 /**
3761 * Experimental features
3762 *
3763 * Features under this field could change in the future and might NOT follow semver.
3764 * Please be careful and always pin Vite's version when using them.
3765 * @experimental
3766 */
3767 experimental?: ExperimentalOptions;
3768 /**
3769 * Options to opt-in to future behavior
3770 */
3771 future?: FutureOptions;
3772 /**
3773 * Legacy options
3774 *
3775 * Features under this field only follow semver for patches, they could be removed in a
3776 * future minor version. Please always pin Vite's version to a minor when using them.
3777 */
3778 legacy?: LegacyOptions;
3779 /**
3780 * Log level.
3781 * @default 'info'
3782 */
3783 logLevel?: LogLevel;
3784 /**
3785 * Custom logger.
3786 */
3787 customLogger?: Logger;
3788 /**
3789 * @default true
3790 */
3791 clearScreen?: boolean;
3792 /**
3793 * Environment files directory. Can be an absolute path, or a path relative from
3794 * root.
3795 * @default root
3796 */
3797 envDir?: string;
3798 /**
3799 * Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
3800 * @default 'VITE_'
3801 */
3802 envPrefix?: string | string[];
3803 /**
3804 * Worker bundle options
3805 */
3806 worker?: {
3807 /**
3808 * Output format for worker bundle
3809 * @default 'iife'
3810 */
3811 format?: 'es' | 'iife';
3812 /**
3813 * Vite plugins that apply to worker bundle. The plugins returned by this function
3814 * should be new instances every time it is called, because they are used for each
3815 * rollup worker bundling process.
3816 */
3817 plugins?: () => PluginOption[];
3818 /**
3819 * Rollup options to build worker bundle
3820 */
3821 rollupOptions?: Omit<RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'>;
3822 };
3823 /**
3824 * Dep optimization options
3825 */
3826 optimizeDeps?: DepOptimizationOptions;
3827 /**
3828 * SSR specific options
3829 * We could make SSROptions be a EnvironmentOptions if we can abstract
3830 * external/noExternal for environments in general.
3831 */
3832 ssr?: SSROptions;
3833 /**
3834 * Environment overrides
3835 */
3836 environments?: Record<string, EnvironmentOptions>;
3837 /**
3838 * Whether your application is a Single Page Application (SPA),
3839 * a Multi-Page Application (MPA), or Custom Application (SSR
3840 * and frameworks with custom HTML handling)
3841 * @default 'spa'
3842 */
3843 appType?: AppType;
3844}
3845interface HTMLOptions {
3846 /**
3847 * A nonce value placeholder that will be used when generating script/style tags.
3848 *
3849 * Make sure that this placeholder will be replaced with a unique value for each request by the server.
3850 */
3851 cspNonce?: string;
3852}
3853interface FutureOptions {
3854 removePluginHookHandleHotUpdate?: 'warn';
3855 removePluginHookSsrArgument?: 'warn';
3856 removeServerModuleGraph?: 'warn';
3857 removeServerHot?: 'warn';
3858 removeServerTransformRequest?: 'warn';
3859 removeSsrLoadModule?: 'warn';
3860}
3861interface ExperimentalOptions {
3862 /**
3863 * Append fake `&lang.(ext)` when queries are specified, to preserve the file extension for following plugins to process.
3864 *
3865 * @experimental
3866 * @default false
3867 */
3868 importGlobRestoreExtension?: boolean;
3869 /**
3870 * Allow finegrain control over assets and public files paths
3871 *
3872 * @experimental
3873 */
3874 renderBuiltUrl?: RenderBuiltAssetUrl;
3875 /**
3876 * Enables support of HMR partial accept via `import.meta.hot.acceptExports`.
3877 *
3878 * @experimental
3879 * @default false
3880 */
3881 hmrPartialAccept?: boolean;
3882 /**
3883 * Skips SSR transform to make it easier to use Vite with Node ESM loaders.
3884 * @warning Enabling this will break normal operation of Vite's SSR in development mode.
3885 *
3886 * @experimental
3887 * @default false
3888 */
3889 skipSsrTransform?: boolean;
3890}
3891interface LegacyOptions {
3892 /**
3893 * In Vite 4, SSR-externalized modules (modules not bundled and loaded by Node.js at runtime)
3894 * are implicitly proxied in dev to automatically handle `default` and `__esModule` access.
3895 * However, this does not correctly reflect how it works in the Node.js runtime, causing
3896 * inconsistencies between dev and prod.
3897 *
3898 * In Vite 5, the proxy is removed so dev and prod are consistent, but if you still require
3899 * the old behaviour, you can enable this option. If so, please leave your feedback at
3900 * https://github.com/vitejs/vite/discussions/14697.
3901 */
3902 proxySsrExternalModules?: boolean;
3903}
3904interface ResolvedWorkerOptions {
3905 format: 'es' | 'iife';
3906 plugins: (bundleChain: string[]) => Promise<ResolvedConfig>;
3907 rollupOptions: RollupOptions;
3908}
3909interface InlineConfig extends UserConfig {
3910 configFile?: string | false;
3911 envFile?: false;
3912}
3913type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'css' | 'json' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build' | 'dev' | 'environments' | 'server' | 'preview'> & {
3914 configFile: string | undefined;
3915 configFileDependencies: string[];
3916 inlineConfig: InlineConfig;
3917 root: string;
3918 base: string;
3919 publicDir: string;
3920 cacheDir: string;
3921 command: 'build' | 'serve';
3922 mode: string;
3923 isWorker: boolean;
3924 isProduction: boolean;
3925 envDir: string;
3926 env: Record<string, any>;
3927 resolve: Required<ResolveOptions> & {
3928 alias: Alias[];
3929 };
3930 plugins: readonly Plugin[];
3931 css: ResolvedCSSOptions;
3932 json: Required<JsonOptions>;
3933 esbuild: ESBuildOptions | false;
3934 server: ResolvedServerOptions;
3935 dev: ResolvedDevEnvironmentOptions;
3936 /** @experimental */
3937 builder: ResolvedBuilderOptions | undefined;
3938 build: ResolvedBuildOptions;
3939 preview: ResolvedPreviewOptions;
3940 ssr: ResolvedSSROptions;
3941 assetsInclude: (file: string) => boolean;
3942 logger: Logger;
3943 createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
3944 optimizeDeps: DepOptimizationOptions;
3945 worker: ResolvedWorkerOptions;
3946 appType: AppType;
3947 experimental: ExperimentalOptions;
3948 environments: Record<string, ResolvedEnvironmentOptions>;
3949} & PluginHookUtils>;
3950interface PluginHookUtils {
3951 getSortedPlugins: <K extends keyof Plugin>(hookName: K) => PluginWithRequiredHook<K>[];
3952 getSortedPluginHooks: <K extends keyof Plugin>(hookName: K) => NonNullable<HookHandler<Plugin[K]>>[];
3953}
3954type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
3955declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string, defaultNodeEnv?: string, isPreview?: boolean,
3956
3957): Promise<ResolvedConfig>;
3958declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]];
3959declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel, customLogger?: Logger): Promise<{
3960 path: string;
3961 config: UserConfig;
3962 dependencies: string[];
3963} | null>;
3964
3965type ResolveIdFn = (environment: PartialEnvironment, id: string, importer?: string, aliasOnly?: boolean) => Promise<string | undefined>;
3966/**
3967 * Create an internal resolver to be used in special scenarios, e.g.
3968 * optimizer and handling css @imports
3969 */
3970declare function createIdResolver(config: ResolvedConfig, options?: Partial<InternalResolveOptions>): ResolveIdFn;
3971
3972declare function buildErrorMessage(err: RollupError, args?: string[], includeStack?: boolean): string;
3973
3974/**
3975 * @experimental
3976 */
3977interface ServerModuleRunnerOptions extends Omit<ModuleRunnerOptions, 'root' | 'fetchModule' | 'hmr' | 'transport'> {
3978 /**
3979 * Disable HMR or configure HMR logger.
3980 */
3981 hmr?: false | {
3982 logger?: ModuleRunnerHmr['logger'];
3983 };
3984 /**
3985 * Provide a custom module evaluator. This controls how the code is executed.
3986 */
3987 evaluator?: ModuleEvaluator;
3988}
3989/**
3990 * Create an instance of the Vite SSR runtime that support HMR.
3991 * @experimental
3992 */
3993declare function createServerModuleRunner(environment: DevEnvironment, options?: ServerModuleRunnerOptions): ModuleRunner;
3994
3995declare function createRunnableDevEnvironment(name: string, config: ResolvedConfig, context?: RunnableDevEnvironmentContext): RunnableDevEnvironment;
3996interface RunnableDevEnvironmentContext extends Omit<DevEnvironmentContext, 'hot'> {
3997 runner?: (environment: RunnableDevEnvironment, options?: ServerModuleRunnerOptions) => ModuleRunner;
3998 runnerOptions?: ServerModuleRunnerOptions;
3999 hot?: boolean;
4000}
4001declare function isRunnableDevEnvironment(environment: Environment): environment is RunnableDevEnvironment;
4002declare class RunnableDevEnvironment extends DevEnvironment {
4003 private _runner;
4004 private _runnerFactory;
4005 private _runnerOptions;
4006 constructor(name: string, config: ResolvedConfig, context: RunnableDevEnvironmentContext);
4007 get runner(): ModuleRunner;
4008 close(): Promise<void>;
4009}
4010
4011interface FetchModuleOptions {
4012 cached?: boolean;
4013 inlineSourceMap?: boolean;
4014 startOffset?: number;
4015}
4016/**
4017 * Fetch module information for Vite runner.
4018 * @experimental
4019 */
4020declare function fetchModule(environment: DevEnvironment, url: string, importer?: string, options?: FetchModuleOptions): Promise<FetchResult>;
4021
4022interface ModuleRunnerTransformOptions {
4023 json?: {
4024 stringify?: boolean;
4025 };
4026}
4027declare function ssrTransform(code: string, inMap: SourceMap | {
4028 mappings: '';
4029} | null, url: string, originalCode: string, options?: ModuleRunnerTransformOptions): Promise<TransformResult | null>;
4030
4031declare const VERSION: string;
4032declare const DEFAULT_CLIENT_MAIN_FIELDS: readonly string[];
4033declare const DEFAULT_SERVER_MAIN_FIELDS: readonly string[];
4034declare const DEFAULT_CLIENT_CONDITIONS: readonly string[];
4035declare const DEFAULT_SERVER_CONDITIONS: readonly string[];
4036
4037declare const isCSSRequest: (request: string) => boolean;
4038/**
4039 * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
4040 */
4041declare class SplitVendorChunkCache {
4042 cache: Map<string, boolean>;
4043 constructor();
4044 reset(): void;
4045}
4046/**
4047 * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
4048 */
4049declare function splitVendorChunk(options?: {
4050 cache?: SplitVendorChunkCache;
4051}): GetManualChunk;
4052/**
4053 * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
4054 */
4055declare function splitVendorChunkPlugin(): Plugin;
4056
4057/**
4058 * Inlined to keep `@rollup/pluginutils` in devDependencies
4059 */
4060type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
4061declare const createFilter: (include?: FilterPattern, exclude?: FilterPattern, options?: {
4062 resolve?: string | false | null;
4063}) => (id: string | unknown) => boolean;
4064declare const rollupVersion: string;
4065declare function normalizePath(id: string): string;
4066declare function 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>;
4067declare function mergeAlias(a?: AliasOptions, b?: AliasOptions): AliasOptions | undefined;
4068
4069interface SendOptions {
4070 etag?: string;
4071 cacheControl?: string;
4072 headers?: OutgoingHttpHeaders;
4073 map?: SourceMap | {
4074 mappings: '';
4075 } | null;
4076}
4077declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions): void;
4078
4079/**
4080 * Search up for the nearest workspace root
4081 */
4082declare function searchForWorkspaceRoot(current: string, root?: string): string;
4083
4084/**
4085 * Check if the url is allowed to be served, via the `server.fs` config.
4086 */
4087declare function isFileServingAllowed(config: ResolvedConfig, url: string): boolean;
4088/**
4089 * @deprecated Use the `isFileServingAllowed(config, url)` signature instead.
4090 */
4091declare function isFileServingAllowed(url: string, server: ViteDevServer): boolean;
4092declare function isFileLoadingAllowed(config: ResolvedConfig, filePath: string): boolean;
4093
4094declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record<string, string>;
4095declare function resolveEnvPrefix({ envPrefix, }: UserConfig): string[];
4096
4097type Manifest = Record<string, ManifestChunk>;
4098interface ManifestChunk {
4099 src?: string;
4100 file: string;
4101 css?: string[];
4102 assets?: string[];
4103 isEntry?: boolean;
4104 name?: string;
4105 isDynamicEntry?: boolean;
4106 imports?: string[];
4107 dynamicImports?: string[];
4108}
4109
4110export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type BindCLIShortcutsOptions, BuildEnvironment, type BuildEnvironmentOptions, type BuildOptions, type BuilderOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, DevEnvironment, type DevEnvironmentContext, type DevEnvironmentOptions, type ESBuildOptions, type ESBuildTransformResult, type Environment, EnvironmentModuleGraph, EnvironmentModuleNode, type EnvironmentOptions, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HotChannel, type HotChannelClient, type HotChannelListener, type HotUpdateOptions, type HtmlTagDescriptor, HttpProxy, type HttpServer, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LessPreprocessorOptions, type LibraryFormats, type LibraryOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type ModuleRunnerTransformOptions, type OptimizedDepInfo, type Plugin, PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildEnvironmentOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedDevEnvironmentOptions, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, RunnableDevEnvironment, type RunnableDevEnvironmentContext, type SSROptions, type SSRTarget, type SassPreprocessorOptions, type SendOptions, type ServerHMRChannel, type ServerHook, type ServerHotChannel, type ServerModuleRunnerOptions, type ServerOptions, type SkipInformation, SplitVendorChunkCache, type SsrDepOptimizationConfig, type StylusPreprocessorOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteBuilder, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createBuilder, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, perEnvironmentPlugin, perEnvironmentState, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };