UNPKG

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