-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
config.ts
1039 lines (957 loc) · 28.7 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 'fs'
import path from 'path'
import type { Plugin } from './plugin'
import type { BuildOptions } from './build'
import { resolveBuildOptions } from './build'
import type { ResolvedServerOptions, ServerOptions } from './server'
import { resolveServerOptions } from './server'
import type { ResolvedPreviewOptions, PreviewOptions } from './preview'
import { resolvePreviewOptions } from './preview'
import type { CSSOptions } from './plugins/css'
import {
arraify,
createDebugger,
isExternalUrl,
isObject,
lookupFile,
normalizePath,
dynamicImport
} from './utils'
import { resolvePlugins } from './plugins'
import colors from 'picocolors'
import type { ESBuildOptions } from './plugins/esbuild'
import dotenv from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import type { Alias, AliasOptions } from 'types/alias'
import { CLIENT_ENTRY, ENV_ENTRY, DEFAULT_ASSETS_RE } from './constants'
import type { InternalResolveOptions, ResolveOptions } from './plugins/resolve'
import { resolvePlugin } from './plugins/resolve'
import type { Logger, LogLevel } from './logger'
import { createLogger } from './logger'
import type { DepOptimizationOptions } from './optimizer'
import { createFilter } from '@rollup/pluginutils'
import type { ResolvedBuildOptions } from '.'
import { parse as parseUrl } from 'url'
import type { JsonOptions } from './plugins/json'
import type { PluginContainer } from './server/pluginContainer'
import { createPluginContainer } from './server/pluginContainer'
import aliasPlugin from '@rollup/plugin-alias'
import { build } from 'esbuild'
import { performance } from 'perf_hooks'
import type { PackageCache } from './packages'
const debug = createDebugger('vite:config')
// NOTE: every export in this file is re-exported from ./index.ts so it will
// be part of the public API.
export interface ConfigEnv {
command: 'build' | 'serve'
mode: string
}
export type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>
export type UserConfigExport = UserConfig | Promise<UserConfig> | 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 that exposes two properties:
* `command` (either `'build'` or `'serve'`), and `mode`.
*/
export function defineConfig(config: UserConfigExport): UserConfigExport {
return config
}
export type PluginOption = Plugin | false | null | undefined
export interface UserConfig {
/**
* 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 <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 <root>.
* @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
/**
* Define global variable replacements.
* Entries will be defined on `window` during dev and replaced during build.
*/
define?: Record<string, any>
/**
* Array of vite plugins to use.
*/
plugins?: (PluginOption | PluginOption[])[]
/**
* Configure resolver
*/
resolve?: ResolveOptions & { alias?: AliasOptions }
/**
* 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
/**
* Specify additional picomatch patterns to be treated as static assets.
*/
assetsInclude?: string | RegExp | (string | RegExp)[]
/**
* Server specific options, e.g. host, port, https...
*/
server?: ServerOptions
/**
* Build specific options
*/
build?: BuildOptions
/**
* Preview specific options, e.g. host, port, https...
*/
preview?: PreviewOptions
/**
* Dep optimization options
*/
optimizeDeps?: DepOptimizationOptions
/**
* SSR specific options
* @alpha
*/
ssr?: SSROptions
/**
* 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
* the location of the config file itself.
* @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[]
/**
* Import aliases
* @deprecated use `resolve.alias` instead
*/
alias?: AliasOptions
/**
* Force Vite to always resolve listed dependencies to the same copy (from
* project root).
* @deprecated use `resolve.dedupe` instead
*/
dedupe?: string[]
}
export type SSRTarget = 'node' | 'webworker'
export interface SSROptions {
external?: string[]
noExternal?: string | RegExp | (string | RegExp)[] | true
/**
* Define the target for the ssr build. The browser field in package.json
* is ignored for node but used if webworker is the target
* Default: 'node'
*/
target?: SSRTarget
}
export interface InlineConfig extends UserConfig {
configFile?: string | false
envFile?: false
}
export type ResolvedConfig = Readonly<
Omit<
UserConfig,
'plugins' | 'alias' | 'dedupe' | 'assetsInclude' | 'optimizeDeps'
> & {
configFile: string | undefined
configFileDependencies: string[]
inlineConfig: InlineConfig
root: string
base: string
publicDir: string
command: 'build' | 'serve'
mode: string
isProduction: boolean
env: Record<string, any>
resolve: ResolveOptions & {
alias: Alias[]
}
plugins: readonly Plugin[]
server: ResolvedServerOptions
build: ResolvedBuildOptions
preview: ResolvedPreviewOptions
assetsInclude: (file: string) => boolean
logger: Logger
createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn
optimizeDeps: Omit<DepOptimizationOptions, 'keepNames'>
/** @internal */
packageCache: PackageCache
}
>
export type ResolveFn = (
id: string,
importer?: string,
aliasOnly?: boolean,
ssr?: boolean
) => Promise<string | undefined>
export async function resolveConfig(
inlineConfig: InlineConfig,
command: 'build' | 'serve',
defaultMode = 'development'
): Promise<ResolvedConfig> {
let config = inlineConfig
let configFileDependencies: string[] = []
let mode = inlineConfig.mode || defaultMode
// some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
// production-specific behavior, so set it here even though we haven't
// resolve the final mode yet
if (mode === 'production') {
process.env.NODE_ENV = 'production'
}
const configEnv = {
mode,
command
}
let { configFile } = config
if (configFile !== false) {
const loadResult = await loadConfigFromFile(
configEnv,
configFile,
config.root,
config.logLevel
)
if (loadResult) {
config = mergeConfig(loadResult.config, config)
configFile = loadResult.path
configFileDependencies = loadResult.dependencies
}
}
// Define logger
const logger = createLogger(config.logLevel, {
allowClearScreen: config.clearScreen,
customLogger: config.customLogger
})
// user config may provide an alternative mode. But --mode has a higher priority
mode = inlineConfig.mode || config.mode || mode
configEnv.mode = mode
// resolve plugins
const rawUserPlugins = (config.plugins || []).flat().filter((p) => {
if (!p) {
return false
} else if (!p.apply) {
return true
} else if (typeof p.apply === 'function') {
return p.apply({ ...config, mode }, configEnv)
} else {
return p.apply === command
}
}) as Plugin[]
const [prePlugins, normalPlugins, postPlugins] =
sortUserPlugins(rawUserPlugins)
// run config hooks
const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]
for (const p of userPlugins) {
if (p.config) {
const res = await p.config(config, configEnv)
if (res) {
config = mergeConfig(config, res)
}
}
}
// resolve root
const resolvedRoot = normalizePath(
config.root ? path.resolve(config.root) : process.cwd()
)
const clientAlias = [
{ find: /^[\/]?@vite\/env/, replacement: () => ENV_ENTRY },
{ find: /^[\/]?@vite\/client/, replacement: () => CLIENT_ENTRY }
]
// resolve alias with internal client alias
const resolvedAlias = mergeAlias(
// @ts-ignore because @rollup/plugin-alias' type doesn't allow function
// replacement, but its implementation does work with function values.
clientAlias,
config.resolve?.alias || config.alias || []
)
const resolveOptions: ResolvedConfig['resolve'] = {
dedupe: config.dedupe,
...config.resolve,
alias: resolvedAlias
}
// load .env files
const envDir = config.envDir
? normalizePath(path.resolve(resolvedRoot, config.envDir))
: resolvedRoot
const userEnv =
inlineConfig.envFile !== false &&
loadEnv(mode, envDir, resolveEnvPrefix(config))
// Note it is possible for user to have a custom mode, e.g. `staging` where
// production-like behavior is expected. This is indicated by NODE_ENV=production
// loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV
const isProduction = (process.env.VITE_USER_NODE_ENV || mode) === 'production'
if (isProduction) {
// in case default mode was not production and is overwritten
process.env.NODE_ENV = 'production'
}
// resolve public base url
const BASE_URL = resolveBaseUrl(config.base, command === 'build', logger)
const resolvedBuildOptions = resolveBuildOptions(
resolvedRoot,
config.build,
command === 'build'
)
// resolve cache directory
const pkgPath = lookupFile(
resolvedRoot,
[`package.json`],
true /* pathOnly */
)
const cacheDir = config.cacheDir
? path.resolve(resolvedRoot, config.cacheDir)
: pkgPath && path.join(path.dirname(pkgPath), `node_modules/.vite`)
const assetsFilter = config.assetsInclude
? createFilter(config.assetsInclude)
: () => false
// create an internal resolver to be used in special scenarios, e.g.
// optimizer & handling css @imports
const createResolver: ResolvedConfig['createResolver'] = (options) => {
let aliasContainer: PluginContainer | undefined
let resolverContainer: PluginContainer | undefined
return async (id, importer, aliasOnly, ssr) => {
let container: PluginContainer
if (aliasOnly) {
container =
aliasContainer ||
(aliasContainer = await createPluginContainer({
...resolved,
plugins: [aliasPlugin({ entries: resolved.resolve.alias })]
}))
} else {
container =
resolverContainer ||
(resolverContainer = await createPluginContainer({
...resolved,
plugins: [
aliasPlugin({ entries: resolved.resolve.alias }),
resolvePlugin({
...resolved.resolve,
root: resolvedRoot,
isProduction,
isBuild: command === 'build',
ssrConfig: resolved.ssr,
asSrc: true,
preferRelative: false,
tryIndex: true,
...options
})
]
}))
}
return (await container.resolveId(id, importer, { ssr }))?.id
}
}
const { publicDir } = config
const resolvedPublicDir =
publicDir !== false && publicDir !== ''
? path.resolve(
resolvedRoot,
typeof publicDir === 'string' ? publicDir : 'public'
)
: ''
const server = resolveServerOptions(resolvedRoot, config.server)
const resolved: ResolvedConfig = {
...config,
configFile: configFile ? normalizePath(configFile) : undefined,
configFileDependencies,
inlineConfig,
root: resolvedRoot,
base: BASE_URL,
resolve: resolveOptions,
publicDir: resolvedPublicDir,
cacheDir,
command,
mode,
isProduction,
plugins: userPlugins,
server,
build: resolvedBuildOptions,
preview: resolvePreviewOptions(config.preview, server),
env: {
...userEnv,
BASE_URL,
MODE: mode,
DEV: !isProduction,
PROD: isProduction
},
assetsInclude(file: string) {
return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file)
},
logger,
packageCache: new Map(),
createResolver,
optimizeDeps: {
...config.optimizeDeps,
esbuildOptions: {
keepNames: config.optimizeDeps?.keepNames,
preserveSymlinks: config.resolve?.preserveSymlinks,
...config.optimizeDeps?.esbuildOptions
}
}
}
;(resolved.plugins as Plugin[]) = await resolvePlugins(
resolved,
prePlugins,
normalPlugins,
postPlugins
)
// call configResolved hooks
await Promise.all(userPlugins.map((p) => p.configResolved?.(resolved)))
if (process.env.DEBUG) {
debug(`using resolved config: %O`, {
...resolved,
plugins: resolved.plugins.map((p) => p.name)
})
}
// TODO Deprecation warnings - remove when out of beta
const logDeprecationWarning = (
deprecatedOption: string,
hint: string,
error?: Error
) => {
logger.warn(
colors.yellow(
colors.bold(
`(!) "${deprecatedOption}" option is deprecated. ${hint}${
error ? `\n${error.stack}` : ''
}`
)
)
)
}
if (config.build?.base) {
logDeprecationWarning(
'build.base',
'"base" is now a root-level config option.'
)
config.base = config.build.base
}
Object.defineProperty(resolvedBuildOptions, 'base', {
enumerable: false,
get() {
logDeprecationWarning(
'build.base',
'"base" is now a root-level config option.',
new Error()
)
return resolved.base
}
})
if (config.alias) {
logDeprecationWarning('alias', 'Use "resolve.alias" instead.')
}
Object.defineProperty(resolved, 'alias', {
enumerable: false,
get() {
logDeprecationWarning(
'alias',
'Use "resolve.alias" instead.',
new Error()
)
return resolved.resolve.alias
}
})
if (config.dedupe) {
logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.')
}
Object.defineProperty(resolved, 'dedupe', {
enumerable: false,
get() {
logDeprecationWarning(
'dedupe',
'Use "resolve.dedupe" instead.',
new Error()
)
return resolved.resolve.dedupe
}
})
if (config.optimizeDeps?.keepNames) {
logDeprecationWarning(
'optimizeDeps.keepNames',
'Use "optimizeDeps.esbuildOptions.keepNames" instead.'
)
}
Object.defineProperty(resolved.optimizeDeps, 'keepNames', {
enumerable: false,
get() {
logDeprecationWarning(
'optimizeDeps.keepNames',
'Use "optimizeDeps.esbuildOptions.keepNames" instead.',
new Error()
)
return resolved.optimizeDeps.esbuildOptions?.keepNames
}
})
if (config.build?.polyfillDynamicImport) {
logDeprecationWarning(
'build.polyfillDynamicImport',
'"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.'
)
}
Object.defineProperty(resolvedBuildOptions, 'polyfillDynamicImport', {
enumerable: false,
get() {
logDeprecationWarning(
'build.polyfillDynamicImport',
'"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.',
new Error()
)
return false
}
})
if (config.build?.cleanCssOptions) {
logDeprecationWarning(
'build.cleanCssOptions',
'Vite now uses esbuild for CSS minification.'
)
}
if (config.build?.terserOptions && config.build.minify === 'esbuild') {
logger.warn(
colors.yellow(
`build.terserOptions is specified but build.minify is not set to use Terser. ` +
`Note Vite now defaults to use esbuild for minification. If you still ` +
`prefer Terser, set build.minify to "terser".`
)
)
}
return resolved
}
/**
* Resolve base. Note that some users use Vite to build for non-web targets like
* electron or expects to deploy
*/
function resolveBaseUrl(
base: UserConfig['base'] = '/',
isBuild: boolean,
logger: Logger
): string {
// #1669 special treatment for empty for same dir relative base
if (base === '' || base === './') {
return isBuild ? base : '/'
}
if (base.startsWith('.')) {
logger.warn(
colors.yellow(
colors.bold(
`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
`URL, ./, or an empty string.`
)
)
)
base = '/'
}
// external URL
if (isExternalUrl(base)) {
if (!isBuild) {
// get base from full url during dev
const parsed = parseUrl(base)
base = parsed.pathname || '/'
}
} else {
// ensure leading slash
if (!base.startsWith('/')) {
logger.warn(
colors.yellow(
colors.bold(`(!) "base" option should start with a slash.`)
)
)
base = '/' + base
}
}
// ensure ending slash
if (!base.endsWith('/')) {
logger.warn(
colors.yellow(colors.bold(`(!) "base" option should end with a slash.`))
)
base += '/'
}
return base
}
function mergeConfigRecursively(
defaults: Record<string, any>,
overrides: Record<string, any>,
rootPath: string
) {
const merged: Record<string, any> = { ...defaults }
for (const key in overrides) {
const value = overrides[key]
if (value == null) {
continue
}
const existing = merged[key]
if (Array.isArray(existing) && Array.isArray(value)) {
merged[key] = [...existing, ...value]
continue
}
if (isObject(existing) && isObject(value)) {
merged[key] = mergeConfigRecursively(
existing,
value,
rootPath ? `${rootPath}.${key}` : key
)
continue
}
// fields that require special handling
if (existing != null) {
if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
merged[key] = mergeAlias(existing, value)
continue
} else if (key === 'assetsInclude' && rootPath === '') {
merged[key] = [].concat(existing, value)
continue
} else if (key === 'noExternal' && existing === true) {
continue
}
}
merged[key] = value
}
return merged
}
export function mergeConfig(
defaults: Record<string, any>,
overrides: Record<string, any>,
isRoot = true
): Record<string, any> {
return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.')
}
function mergeAlias(a: AliasOptions = [], b: AliasOptions = []): Alias[] {
return [...normalizeAlias(a), ...normalizeAlias(b)]
}
function normalizeAlias(o: AliasOptions): Alias[] {
return Array.isArray(o)
? o.map(normalizeSingleAlias)
: Object.keys(o).map((find) =>
normalizeSingleAlias({
find,
replacement: (o as any)[find]
})
)
}
// https://github.com/vitejs/vite/issues/1363
// work around https://github.com/rollup/plugins/issues/759
function normalizeSingleAlias({ find, replacement }: Alias): Alias {
if (
typeof find === 'string' &&
find.endsWith('/') &&
replacement.endsWith('/')
) {
find = find.slice(0, find.length - 1)
replacement = replacement.slice(0, replacement.length - 1)
}
return { find, replacement }
}
export function sortUserPlugins(
plugins: (Plugin | Plugin[])[] | undefined
): [Plugin[], Plugin[], Plugin[]] {
const prePlugins: Plugin[] = []
const postPlugins: Plugin[] = []
const normalPlugins: Plugin[] = []
if (plugins) {
plugins.flat().forEach((p) => {
if (p.enforce === 'pre') prePlugins.push(p)
else if (p.enforce === 'post') postPlugins.push(p)
else normalPlugins.push(p)
})
}
return [prePlugins, normalPlugins, postPlugins]
}
export async function loadConfigFromFile(
configEnv: ConfigEnv,
configFile?: string,
configRoot: string = process.cwd(),
logLevel?: LogLevel
): Promise<{
path: string
config: UserConfig
dependencies: string[]
} | null> {
const start = performance.now()
const getTime = () => `${(performance.now() - start).toFixed(2)}ms`
let resolvedPath: string | undefined
let isTS = false
let isESM = false
let dependencies: string[] = []
// check package.json for type: "module" and set `isMjs` to true
try {
const pkg = lookupFile(configRoot, ['package.json'])
if (pkg && JSON.parse(pkg).type === 'module') {
isESM = true
}
} catch (e) {}
if (configFile) {
// explicit config path is always resolved from cwd
resolvedPath = path.resolve(configFile)
isTS = configFile.endsWith('.ts')
if (configFile.endsWith('.mjs')) {
isESM = true
}
} else {
// implicit config file loaded from inline root (if present)
// otherwise from cwd
const jsconfigFile = path.resolve(configRoot, 'vite.config.js')
if (fs.existsSync(jsconfigFile)) {
resolvedPath = jsconfigFile
}
if (!resolvedPath) {
const mjsconfigFile = path.resolve(configRoot, 'vite.config.mjs')
if (fs.existsSync(mjsconfigFile)) {
resolvedPath = mjsconfigFile
isESM = true
}
}
if (!resolvedPath) {
const tsconfigFile = path.resolve(configRoot, 'vite.config.ts')
if (fs.existsSync(tsconfigFile)) {
resolvedPath = tsconfigFile
isTS = true
}
}
}
if (!resolvedPath) {
debug('no config file found.')
return null
}
try {
let userConfig: UserConfigExport | undefined
if (isESM) {
const fileUrl = require('url').pathToFileURL(resolvedPath)
const bundled = await bundleConfigFile(resolvedPath, true)
dependencies = bundled.dependencies
if (isTS) {
// before we can register loaders without requiring users to run node
// with --experimental-loader themselves, we have to do a hack here:
// bundle the config file w/ ts transforms first, write it to disk,
// load it with native Node ESM, then delete the file.
fs.writeFileSync(resolvedPath + '.js', bundled.code)
userConfig = (await dynamicImport(`${fileUrl}.js?t=${Date.now()}`))
.default
fs.unlinkSync(resolvedPath + '.js')
debug(`TS + native esm config loaded in ${getTime()}`, fileUrl)
} else {
// using Function to avoid this from being compiled away by TS/Rollup
// append a query so that we force reload fresh config in case of
// server restart
userConfig = (await dynamicImport(`${fileUrl}?t=${Date.now()}`)).default
debug(`native esm config loaded in ${getTime()}`, fileUrl)
}
}
if (!userConfig) {
// Bundle config file and transpile it to cjs using esbuild.
const bundled = await bundleConfigFile(resolvedPath)
dependencies = bundled.dependencies
userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code)
debug(`bundled config file loaded in ${getTime()}`)
}
const config = await (typeof userConfig === 'function'
? userConfig(configEnv)
: userConfig)
if (!isObject(config)) {
throw new Error(`config must export or return an object.`)
}
return {
path: normalizePath(resolvedPath),
config,
dependencies
}
} catch (e) {
createLogger(logLevel).error(
colors.red(`failed to load config from ${resolvedPath}`),
{ error: e }
)
throw e
}
}
async function bundleConfigFile(
fileName: string,
isESM = false
): Promise<{ code: string; dependencies: string[] }> {
const result = await build({
absWorkingDir: process.cwd(),
entryPoints: [fileName],
outfile: 'out.js',
write: false,
platform: 'node',
bundle: true,
format: isESM ? 'esm' : 'cjs',
sourcemap: 'inline',
metafile: true,
plugins: [
{
name: 'externalize-deps',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
const id = args.path
if (id[0] !== '.' && !path.isAbsolute(id)) {
return {
external: true
}
}
})
}
},
{
name: 'replace-import-meta',
setup(build) {
build.onLoad({ filter: /\.[jt]s$/ }, async (args) => {
const contents = await fs.promises.readFile(args.path, 'utf8')
return {
loader: args.path.endsWith('.ts') ? 'ts' : 'js',
contents: contents
.replace(
/\bimport\.meta\.url\b/g,
JSON.stringify(`file://${args.path}`)
)
.replace(
/\b__dirname\b/g,
JSON.stringify(path.dirname(args.path))
)
.replace(/\b__filename\b/g, JSON.stringify(args.path))
}
})
}
}
]
})
const { text } = result.outputFiles[0]
return {
code: text,
dependencies: result.metafile ? Object.keys(result.metafile.inputs) : []
}
}
interface NodeModuleWithCompile extends NodeModule {
_compile(code: string, filename: string): any
}
async function loadConfigFromBundledFile(
fileName: string,
bundledCode: string
): Promise<UserConfig> {
const extension = path.extname(fileName)
const defaultLoader = require.extensions[extension]!
require.extensions[extension] = (module: NodeModule, filename: string) => {
if (filename === fileName) {
;(module as NodeModuleWithCompile)._compile(bundledCode, filename)
} else {
defaultLoader(module, filename)
}
}
// clear cache in case of server restart
delete require.cache[require.resolve(fileName)]
const raw = require(fileName)
const config = raw.__esModule ? raw.default : raw
require.extensions[extension] = defaultLoader
return config
}
export function loadEnv(
mode: string,
envDir: string,
prefixes: string | string[] = 'VITE_'
): Record<string, string> {
if (mode === 'local') {
throw new Error(
`"local" cannot be used as a mode name because it conflicts with ` +
`the .local postfix for .env files.`
)
}
prefixes = arraify(prefixes)
const env: Record<string, string> = {}
const envFiles = [
/** mode local file */ `.env.${mode}.local`,
/** mode file */ `.env.${mode}`,
/** local file */ `.env.local`,
/** default file */ `.env`
]
// check if there are actual env variables starting with VITE_*
// these are typically provided inline and should be prioritized
for (const key in process.env) {
if (
prefixes.some((prefix) => key.startsWith(prefix)) &&
env[key] === undefined
) {
env[key] = process.env[key] as string
}
}
for (const file of envFiles) {
const path = lookupFile(envDir, [file], true)
if (path) {