forked from vitejs/vite
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconfig.ts
2184 lines (2018 loc) · 64.6 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { promisify } from 'node:util'
import { performance } from 'node:perf_hooks'
import { createRequire } from 'node:module'
import colors from 'picocolors'
import type { Alias, AliasOptions } from 'dep-types/alias'
import { rolldown } from 'rolldown'
import type { OutputChunk, RollupOptions } from 'rolldown'
import picomatch from 'picomatch'
import type { AnymatchFn } from '../types/anymatch'
import { withTrailingSlash } from '../shared/utils'
import {
CLIENT_ENTRY,
DEFAULT_ASSETS_RE,
DEFAULT_CLIENT_CONDITIONS,
DEFAULT_CLIENT_MAIN_FIELDS,
DEFAULT_CONFIG_FILES,
DEFAULT_PREVIEW_PORT,
DEFAULT_SERVER_CONDITIONS,
DEFAULT_SERVER_MAIN_FIELDS,
ENV_ENTRY,
FS_PREFIX,
} from './constants'
import type {
FalsyPlugin,
HookHandler,
Plugin,
PluginOption,
PluginWithRequiredHook,
} from './plugin'
import type {
BuildEnvironmentOptions,
BuilderOptions,
RenderBuiltAssetUrl,
ResolvedBuildEnvironmentOptions,
ResolvedBuildOptions,
ResolvedBuilderOptions,
} from './build'
import {
buildEnvironmentOptionsDefaults,
builderOptionsDefaults,
resolveBuildEnvironmentOptions,
resolveBuilderOptions,
} from './build'
import type { ResolvedServerOptions, ServerOptions } from './server'
import { resolveServerOptions, serverConfigDefaults } from './server'
import { DevEnvironment } from './server/environment'
import { createRunnableDevEnvironment } from './server/environments/runnableEnvironment'
import type { WebSocketServer } from './server/ws'
import type { PreviewOptions, ResolvedPreviewOptions } from './preview'
import { resolvePreviewOptions } from './preview'
import {
type CSSOptions,
type ResolvedCSSOptions,
cssConfigDefaults,
resolveCSSOptions,
} from './plugins/css'
import {
asyncFlatten,
createDebugger,
createFilter,
isBuiltin,
isExternalUrl,
isFilePathESM,
isInNodeModules,
isNodeBuiltin,
isObject,
isParentDirectory,
mergeAlias,
mergeConfig,
mergeWithDefaults,
normalizeAlias,
normalizePath,
} from './utils'
import {
createPluginHookUtils,
getHookHandler,
getSortedPluginsByHook,
resolvePlugins,
} from './plugins'
import type { ESBuildOptions } from './plugins/esbuild'
import type {
EnvironmentResolveOptions,
InternalResolveOptions,
ResolveOptions,
} from './plugins/resolve'
import { tryNodeResolve } from './plugins/resolve'
import type { LogLevel, Logger } from './logger'
import { createLogger } from './logger'
import type { DepOptimizationOptions } from './optimizer'
import type { JsonOptions } from './plugins/json'
import type { PackageCache } from './packages'
import { findNearestNodeModules, findNearestPackageData } from './packages'
import { loadEnv, resolveEnvPrefix } from './env'
import type { ResolvedSSROptions, SSROptions } from './ssr'
import { resolveSSROptions, ssrConfigDefaults } from './ssr'
import { PartialEnvironment } from './baseEnvironment'
import { createIdResolver } from './idResolver'
import { type OxcOptions, convertEsbuildConfigToOxcConfig } from './plugins/oxc'
const debug = createDebugger('vite:config', { depth: 10 })
const promisifiedRealpath = promisify(fs.realpath)
export interface ConfigEnv {
/**
* 'serve': during dev (`vite` command)
* 'build': when building for production (`vite build` command)
*/
command: 'build' | 'serve'
mode: string
isSsrBuild?: boolean
isPreview?: boolean
}
/**
* spa: include SPA fallback middleware and configure sirv with `single: true` in preview
*
* mpa: only include non-SPA HTML middlewares
*
* custom: don't include HTML middlewares
*/
export type AppType = 'spa' | 'mpa' | 'custom'
export type UserConfigFnObject = (env: ConfigEnv) => UserConfig
export type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>
export type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>
export type UserConfigExport =
| UserConfig
| Promise<UserConfig>
| UserConfigFnObject
| UserConfigFnPromise
| UserConfigFn
/**
* Type helper to make it easier to use vite.config.ts
* accepts a direct {@link UserConfig} object, or a function that returns it.
* The function receives a {@link ConfigEnv} object.
*/
export function defineConfig(config: UserConfig): UserConfig
export function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>
export function defineConfig(config: UserConfigFnObject): UserConfigFnObject
export function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise
export function defineConfig(config: UserConfigFn): UserConfigFn
export function defineConfig(config: UserConfigExport): UserConfigExport
export function defineConfig(config: UserConfigExport): UserConfigExport {
return config
}
export interface CreateDevEnvironmentContext {
ws: WebSocketServer
}
export interface DevEnvironmentOptions {
/**
* Files to be pre-transformed. Supports glob patterns.
*/
warmup?: string[]
/**
* Pre-transform known direct imports
* defaults to true for the client environment, false for the rest
*/
preTransformRequests?: boolean
/**
* Enables sourcemaps during dev
* @default { js: true }
* @experimental
*/
sourcemap?: boolean | { js?: boolean; css?: boolean }
/**
* Whether or not to ignore-list source files in the dev server sourcemap, used to populate
* the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
*
* By default, it excludes all paths containing `node_modules`. You can pass `false` to
* disable this behavior, or, for full control, a function that takes the source path and
* sourcemap path and returns whether to ignore the source path.
*/
sourcemapIgnoreList?:
| false
| ((sourcePath: string, sourcemapPath: string) => boolean)
/**
* create the Dev Environment instance
*/
createEnvironment?: (
name: string,
config: ResolvedConfig,
context: CreateDevEnvironmentContext,
) => Promise<DevEnvironment> | DevEnvironment
/**
* For environments that support a full-reload, like the client, we can short-circuit when
* restarting the server throwing early to stop processing current files. We avoided this for
* SSR requests. Maybe this is no longer needed.
* @experimental
*/
recoverable?: boolean
/**
* For environments associated with a module runner.
* By default it is true for the client environment and false for non-client environments.
* This option can also be used instead of the removed config.experimental.skipSsrTransform.
*/
moduleRunnerTransform?: boolean
}
function defaultCreateClientDevEnvironment(
name: string,
config: ResolvedConfig,
context: CreateDevEnvironmentContext,
) {
return new DevEnvironment(name, config, {
hot: true,
transport: context.ws,
})
}
function defaultCreateDevEnvironment(name: string, config: ResolvedConfig) {
return createRunnableDevEnvironment(name, config)
}
export type ResolvedDevEnvironmentOptions = Omit<
Required<DevEnvironmentOptions>,
'sourcemapIgnoreList'
> & {
sourcemapIgnoreList: Exclude<
DevEnvironmentOptions['sourcemapIgnoreList'],
false | undefined
>
}
type AllResolveOptions = ResolveOptions & {
alias?: AliasOptions
}
type ResolvedAllResolveOptions = Required<ResolveOptions> & { alias: Alias[] }
export interface SharedEnvironmentOptions {
/**
* Define global variable replacements.
* Entries will be defined on `window` during dev and replaced during build.
*/
define?: Record<string, any>
/**
* Configure resolver
*/
resolve?: EnvironmentResolveOptions
/**
* Define if this environment is used for Server Side Rendering
* @default 'server' if it isn't the client environment
*/
consumer?: 'client' | 'server'
/**
* If true, `process.env` referenced in code will be preserved as-is and evaluated in runtime.
* Otherwise, it is statically replaced as an empty object.
*/
keepProcessEnv?: boolean
/**
* Optimize deps config
*/
optimizeDeps?: DepOptimizationOptions
}
export interface EnvironmentOptions extends SharedEnvironmentOptions {
/**
* Dev specific options
*/
dev?: DevEnvironmentOptions
/**
* Build specific options
*/
build?: BuildEnvironmentOptions
}
export type ResolvedResolveOptions = Required<ResolveOptions>
export type ResolvedEnvironmentOptions = {
define?: Record<string, any>
resolve: ResolvedResolveOptions
consumer: 'client' | 'server'
keepProcessEnv?: boolean
optimizeDeps: DepOptimizationOptions
dev: ResolvedDevEnvironmentOptions
build: ResolvedBuildEnvironmentOptions
}
export type DefaultEnvironmentOptions = Omit<
EnvironmentOptions,
'consumer' | 'resolve'
> & {
resolve?: AllResolveOptions
}
export interface UserConfig extends DefaultEnvironmentOptions {
/**
* Project root directory. Can be an absolute path, or a path relative from
* the location of the config file itself.
* @default process.cwd()
*/
root?: string
/**
* Base public path when served in development or production.
* @default '/'
*/
base?: string
/**
* Directory to serve as plain static assets. Files in this directory are
* served and copied to build dist dir as-is without transform. The value
* can be either an absolute file system path or a path relative to project root.
*
* Set to `false` or an empty string to disable copied static assets to build dist dir.
* @default 'public'
*/
publicDir?: string | false
/**
* Directory to save cache files. Files in this directory are pre-bundled
* deps or some other cache files that generated by vite, which can improve
* the performance. You can use `--force` flag or manually delete the directory
* to regenerate the cache files. The value can be either an absolute file
* system path or a path relative to project root.
* Default to `.vite` when no `package.json` is detected.
* @default 'node_modules/.vite'
*/
cacheDir?: string
/**
* Explicitly set a mode to run in. This will override the default mode for
* each command, and can be overridden by the command line --mode option.
*/
mode?: string
/**
* Array of vite plugins to use.
*/
plugins?: PluginOption[]
/**
* HTML related options
*/
html?: HTMLOptions
/**
* CSS related options (preprocessors and CSS modules)
*/
css?: CSSOptions
/**
* JSON loading options
*/
json?: JsonOptions
/**
* Transform options to pass to esbuild.
* Or set to `false` to disable esbuild.
*/
esbuild?: ESBuildOptions | false
/**
* Transform options to pass to esbuild.
* Or set to `false` to disable esbuild.
*/
oxc?: OxcOptions | false
/**
* Specify additional picomatch patterns to be treated as static assets.
*/
assetsInclude?: string | RegExp | (string | RegExp)[]
/**
* Builder specific options
* @experimental
*/
builder?: BuilderOptions
/**
* Server specific options, e.g. host, port, https...
*/
server?: ServerOptions
/**
* Preview specific options, e.g. host, port, https...
*/
preview?: PreviewOptions
/**
* Experimental features
*
* Features under this field could change in the future and might NOT follow semver.
* Please be careful and always pin Vite's version when using them.
* @experimental
*/
experimental?: ExperimentalOptions
/**
* Options to opt-in to future behavior
*/
future?: FutureOptions
/**
* Legacy options
*
* Features under this field only follow semver for patches, they could be removed in a
* future minor version. Please always pin Vite's version to a minor when using them.
*/
legacy?: LegacyOptions
/**
* Log level.
* @default 'info'
*/
logLevel?: LogLevel
/**
* Custom logger.
*/
customLogger?: Logger
/**
* @default true
*/
clearScreen?: boolean
/**
* Environment files directory. Can be an absolute path, or a path relative from
* root.
* @default root
*/
envDir?: string
/**
* Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
* @default 'VITE_'
*/
envPrefix?: string | string[]
/**
* Worker bundle options
*/
worker?: {
/**
* Output format for worker bundle
* @default 'iife'
*/
format?: 'es' | 'iife'
/**
* Vite plugins that apply to worker bundle. The plugins returned by this function
* should be new instances every time it is called, because they are used for each
* rollup worker bundling process.
*/
plugins?: () => PluginOption[]
/**
* Rollup options to build worker bundle
*/
rollupOptions?: Omit<
RollupOptions,
'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'
>
}
/**
* Dep optimization options
*/
optimizeDeps?: DepOptimizationOptions
/**
* SSR specific options
* We could make SSROptions be a EnvironmentOptions if we can abstract
* external/noExternal for environments in general.
*/
ssr?: SSROptions
/**
* Environment overrides
*/
environments?: Record<string, EnvironmentOptions>
/**
* Whether your application is a Single Page Application (SPA),
* a Multi-Page Application (MPA), or Custom Application (SSR
* and frameworks with custom HTML handling)
* @default 'spa'
*/
appType?: AppType
}
export interface HTMLOptions {
/**
* A nonce value placeholder that will be used when generating script/style tags.
*
* Make sure that this placeholder will be replaced with a unique value for each request by the server.
*/
cspNonce?: string
}
export interface FutureOptions {
removePluginHookHandleHotUpdate?: 'warn'
removePluginHookSsrArgument?: 'warn'
removeServerModuleGraph?: 'warn'
removeServerHot?: 'warn'
removeServerTransformRequest?: 'warn'
removeSsrLoadModule?: 'warn'
}
export interface ExperimentalOptions {
/**
* Append fake `&lang.(ext)` when queries are specified, to preserve the file extension for following plugins to process.
*
* @experimental
* @default false
*/
importGlobRestoreExtension?: boolean
/**
* Allow finegrain control over assets and public files paths
*
* @experimental
*/
renderBuiltUrl?: RenderBuiltAssetUrl
/**
* Enables support of HMR partial accept via `import.meta.hot.acceptExports`.
*
* @experimental
* @default false
*/
hmrPartialAccept?: boolean
/**
* Skips SSR transform to make it easier to use Vite with Node ESM loaders.
* @warning Enabling this will break normal operation of Vite's SSR in development mode.
*
* @experimental
* @default false
*/
skipSsrTransform?: boolean
/**
* Enable builtin plugin that written by rust, which is faster than js plugin.
*
* @experimental
* @default true
*/
enableNativePlugin?: boolean
}
export interface LegacyOptions {
/**
* In Vite 4, SSR-externalized modules (modules not bundled and loaded by Node.js at runtime)
* are implicitly proxied in dev to automatically handle `default` and `__esModule` access.
* However, this does not correctly reflect how it works in the Node.js runtime, causing
* inconsistencies between dev and prod.
*
* In Vite 5, the proxy is removed so dev and prod are consistent, but if you still require
* the old behaviour, you can enable this option. If so, please leave your feedback at
* https://github.com/vitejs/vite/discussions/14697.
*/
proxySsrExternalModules?: boolean
}
export interface ResolvedWorkerOptions {
format: 'es' | 'iife'
plugins: (bundleChain: string[]) => Promise<ResolvedConfig>
rollupOptions: RollupOptions
}
export interface InlineConfig extends UserConfig {
configFile?: string | false
envFile?: false
}
export type ResolvedConfig = Readonly<
Omit<
UserConfig,
| 'plugins'
| 'css'
| 'json'
| 'assetsInclude'
| 'optimizeDeps'
| 'worker'
| 'build'
| 'dev'
| 'environments'
| 'server'
| 'preview'
> & {
configFile: string | undefined
configFileDependencies: string[]
inlineConfig: InlineConfig
root: string
base: string
/** @internal */
decodedBase: string
/** @internal */
rawBase: string
publicDir: string
cacheDir: string
command: 'build' | 'serve'
mode: string
isWorker: boolean
// in nested worker bundle to find the main config
/** @internal */
mainConfig: ResolvedConfig | null
/** @internal list of bundle entry id. used to detect recursive worker bundle. */
bundleChain: string[]
isProduction: boolean
envDir: string
env: Record<string, any>
resolve: Required<ResolveOptions> & {
alias: Alias[]
}
plugins: readonly Plugin[]
css: ResolvedCSSOptions
json: Required<JsonOptions>
// esbuild: ESBuildOptions | false
oxc: OxcOptions | false
server: ResolvedServerOptions
dev: ResolvedDevEnvironmentOptions
/** @experimental */
builder: ResolvedBuilderOptions | undefined
build: ResolvedBuildOptions
preview: ResolvedPreviewOptions
ssr: ResolvedSSROptions
assetsInclude: (file: string) => boolean
logger: Logger
createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn
optimizeDeps: DepOptimizationOptions
/** @internal */
packageCache: PackageCache
worker: ResolvedWorkerOptions
appType: AppType
experimental: ExperimentalOptions
environments: Record<string, ResolvedEnvironmentOptions>
/** @internal */
fsDenyGlob: AnymatchFn
/** @internal */
safeModulePaths: Set<string>
} & PluginHookUtils
>
// inferred ones are omitted
export const configDefaults = Object.freeze({
define: {},
dev: {
warmup: [],
// preTransformRequests
/** @experimental */
sourcemap: { js: true },
sourcemapIgnoreList: undefined,
// createEnvironment
// recoverable
// moduleRunnerTransform
},
build: buildEnvironmentOptionsDefaults,
resolve: {
// mainFields
// conditions
externalConditions: ['node'],
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
dedupe: [],
/** @experimental */
noExternal: [],
external: [],
preserveSymlinks: false,
alias: [],
},
// root
base: '/',
publicDir: 'public',
// cacheDir
// mode
plugins: [],
html: {
cspNonce: undefined,
},
css: cssConfigDefaults,
json: {
namedExports: true,
stringify: 'auto',
},
// esbuild
assetsInclude: undefined,
/** @experimental */
builder: builderOptionsDefaults,
server: serverConfigDefaults,
preview: {
port: DEFAULT_PREVIEW_PORT,
// strictPort
// host
// https
// open
// proxy
// cors
// headers
},
/** @experimental */
experimental: {
importGlobRestoreExtension: false,
renderBuiltUrl: undefined,
hmrPartialAccept: false,
skipSsrTransform: false,
},
future: {
removePluginHookHandleHotUpdate: undefined,
removePluginHookSsrArgument: undefined,
removeServerModuleGraph: undefined,
removeServerHot: undefined,
removeServerTransformRequest: undefined,
removeSsrLoadModule: undefined,
},
legacy: {
proxySsrExternalModules: false,
},
logLevel: 'info',
customLogger: undefined,
clearScreen: true,
envDir: undefined,
envPrefix: 'VITE_',
worker: {
format: 'iife',
plugins: () => [],
// rollupOptions
},
optimizeDeps: {
include: [],
exclude: [],
needsInterop: [],
// esbuildOptions
rollupOptions: {},
/** @experimental */
extensions: [],
/** @deprecated @experimental */
disabled: 'build',
// noDiscovery
/** @experimental */
holdUntilCrawlEnd: true,
// entries
/** @experimental */
force: false,
},
ssr: ssrConfigDefaults,
environments: {},
appType: 'spa',
} satisfies UserConfig)
export function resolveDevEnvironmentOptions(
dev: DevEnvironmentOptions | undefined,
environmentName: string | undefined,
consumer: 'client' | 'server' | undefined,
// Backward compatibility
skipSsrTransform?: boolean,
): ResolvedDevEnvironmentOptions {
const resolved = mergeWithDefaults(
{
...configDefaults.dev,
sourcemapIgnoreList: isInNodeModules,
preTransformRequests: consumer === 'client',
createEnvironment:
environmentName === 'client'
? defaultCreateClientDevEnvironment
: defaultCreateDevEnvironment,
recoverable: consumer === 'client',
moduleRunnerTransform:
skipSsrTransform !== undefined && consumer === 'server'
? skipSsrTransform
: consumer === 'server',
},
dev ?? {},
)
return {
...resolved,
sourcemapIgnoreList:
resolved.sourcemapIgnoreList === false
? () => false
: resolved.sourcemapIgnoreList,
}
}
function resolveEnvironmentOptions(
options: EnvironmentOptions,
alias: Alias[],
preserveSymlinks: boolean,
logger: Logger,
environmentName: string,
// Backward compatibility
skipSsrTransform?: boolean,
isSsrTargetWebworkerSet?: boolean,
): ResolvedEnvironmentOptions {
const isClientEnvironment = environmentName === 'client'
const consumer =
options.consumer ?? (isClientEnvironment ? 'client' : 'server')
const isSsrTargetWebworkerEnvironment =
isSsrTargetWebworkerSet && environmentName === 'ssr'
const resolve = resolveEnvironmentResolveOptions(
options.resolve,
alias,
preserveSymlinks,
logger,
consumer,
isSsrTargetWebworkerEnvironment,
)
return {
define: options.define,
resolve,
keepProcessEnv:
options.keepProcessEnv ??
(isSsrTargetWebworkerEnvironment ? false : consumer === 'server'),
consumer,
optimizeDeps: resolveDepOptimizationOptions(
options.optimizeDeps,
resolve.preserveSymlinks,
consumer,
logger,
),
dev: resolveDevEnvironmentOptions(
options.dev,
environmentName,
consumer,
skipSsrTransform,
),
build: resolveBuildEnvironmentOptions(
options.build ?? {},
logger,
consumer,
),
}
}
export function getDefaultEnvironmentOptions(
config: UserConfig,
): EnvironmentOptions {
return {
define: config.define,
resolve: {
...config.resolve,
// mainFields and conditions are not inherited
mainFields: undefined,
conditions: undefined,
},
dev: config.dev,
build: config.build,
}
}
export interface PluginHookUtils {
getSortedPlugins: <K extends keyof Plugin>(
hookName: K,
) => PluginWithRequiredHook<K>[]
getSortedPluginHooks: <K extends keyof Plugin>(
hookName: K,
) => NonNullable<HookHandler<Plugin[K]>>[]
}
export type ResolveFn = (
id: string,
importer?: string,
aliasOnly?: boolean,
ssr?: boolean,
) => Promise<string | undefined>
/**
* Check and warn if `path` includes characters that don't work well in Vite,
* such as `#` and `?`.
*/
function checkBadCharactersInPath(path: string, logger: Logger): void {
const badChars = []
if (path.includes('#')) {
badChars.push('#')
}
if (path.includes('?')) {
badChars.push('?')
}
if (badChars.length > 0) {
const charString = badChars.map((c) => `"${c}"`).join(' and ')
const inflectedChars = badChars.length > 1 ? 'characters' : 'character'
logger.warn(
colors.yellow(
`The project root contains the ${charString} ${inflectedChars} (${colors.cyan(
path,
)}), which may not work when running Vite. Consider renaming the directory to remove the characters.`,
),
)
}
}
const clientAlias = [
{
find: /^\/?@vite\/env/,
replacement: path.posix.join(FS_PREFIX, normalizePath(ENV_ENTRY)),
},
{
find: /^\/?@vite\/client/,
replacement: path.posix.join(FS_PREFIX, normalizePath(CLIENT_ENTRY)),
},
]
/**
* alias and preserveSymlinks are not per-environment options, but they are
* included in the resolved environment options for convenience.
*/
function resolveEnvironmentResolveOptions(
resolve: EnvironmentResolveOptions | undefined,
alias: Alias[],
preserveSymlinks: boolean,
logger: Logger,
consumer: 'client' | 'server' | undefined,
// Backward compatibility
isSsrTargetWebworkerEnvironment?: boolean,
): ResolvedAllResolveOptions {
const resolvedResolve: ResolvedAllResolveOptions = mergeWithDefaults(
{
...configDefaults.resolve,
mainFields:
consumer === 'client' || isSsrTargetWebworkerEnvironment
? DEFAULT_CLIENT_MAIN_FIELDS
: DEFAULT_SERVER_MAIN_FIELDS,
conditions:
consumer === 'client' || isSsrTargetWebworkerEnvironment
? DEFAULT_CLIENT_CONDITIONS
: DEFAULT_SERVER_CONDITIONS.filter((c) => c !== 'browser'),
enableBuiltinNoExternalCheck: !!isSsrTargetWebworkerEnvironment,
},
resolve ?? {},
)
resolvedResolve.preserveSymlinks = preserveSymlinks
resolvedResolve.alias = alias
if (
// @ts-expect-error removed field
resolve?.browserField === false &&
resolvedResolve.mainFields.includes('browser')
) {
logger.warn(
colors.yellow(
`\`resolve.browserField\` is set to false, but the option is removed in favour of ` +
`the 'browser' string in \`resolve.mainFields\`. You may want to update \`resolve.mainFields\` ` +
`to remove the 'browser' string and preserve the previous browser behaviour.`,
),
)
}
return resolvedResolve
}
function resolveResolveOptions(
resolve: AllResolveOptions | undefined,
logger: Logger,
): ResolvedAllResolveOptions {
// resolve alias with internal client alias
const alias = normalizeAlias(
mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias),
)
const preserveSymlinks =
resolve?.preserveSymlinks ?? configDefaults.resolve.preserveSymlinks
if (alias.some((a) => a.find === '/')) {
logger.warn(
colors.yellow(
`\`resolve.alias\` contains an alias that maps \`/\`. ` +
`This is not recommended as it can cause unexpected behavior when resolving paths.`,
),
)
}
return resolveEnvironmentResolveOptions(
resolve,
alias,
preserveSymlinks,
logger,
undefined,
)
}
// TODO: Introduce ResolvedDepOptimizationOptions
function resolveDepOptimizationOptions(
optimizeDeps: DepOptimizationOptions | undefined,
preserveSymlinks: boolean,
consumer: 'client' | 'server' | undefined,
logger: Logger,
): DepOptimizationOptions {
if (optimizeDeps?.esbuildOptions) {
logger.warn(
colors.yellow(
`You have set \`optimizeDeps.esbuildOptions\` but this options is now deprecated. ` +
`Vite now uses Rolldown to optimize the dependencies. ` +
`Please use \`optimizeDeps.rollupOptions\` instead.`,
),
)
optimizeDeps.rollupOptions ??= {}
optimizeDeps.rollupOptions.resolve ??= {}
optimizeDeps.rollupOptions.output ??= {}
const setResolveOptions = <
T extends keyof Exclude<RollupOptions['resolve'], undefined>,
>(
key: T,
value: Exclude<RollupOptions['resolve'], undefined>[T],
) => {
if (
value !== undefined &&
optimizeDeps.rollupOptions!.resolve![key] === undefined
) {
optimizeDeps.rollupOptions!.resolve![key] = value
}
}
if (
optimizeDeps.esbuildOptions.minify !== undefined &&
optimizeDeps.rollupOptions.output.minify === undefined
) {
optimizeDeps.rollupOptions.output.minify =
optimizeDeps.esbuildOptions.minify
}
if (
optimizeDeps.esbuildOptions.treeShaking !== undefined &&
optimizeDeps.rollupOptions.treeshake === undefined
) {
optimizeDeps.rollupOptions.treeshake =
optimizeDeps.esbuildOptions.treeShaking