/
config.ts
722 lines (654 loc) · 19.1 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
import fs from 'fs'
import path from 'path'
import { Plugin } from './plugin'
import Rollup from 'rollup'
import { BuildOptions, resolveBuildOptions } from './build'
import { ServerOptions } from './server'
import { CSSOptions } from './plugins/css'
import {
createDebugger,
isExternalUrl,
isObject,
lookupFile,
normalizePath
} from './utils'
import { resolvePlugins } from './plugins'
import chalk from 'chalk'
import {
ESBuildOptions,
esbuildPlugin,
stopService,
transformWithEsbuild
} from './plugins/esbuild'
import dotenv from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import { Alias, AliasOptions } from 'types/alias'
import { CLIENT_DIR, DEFAULT_ASSETS_RE, DEP_CACHE_DIR } from './constants'
import { resolvePlugin } from './plugins/resolve'
import { createLogger, Logger, LogLevel } from './logger'
import { DepOptimizationOptions } from './optimizer'
import { createFilter } from '@rollup/pluginutils'
import { ResolvedBuildOptions } from '.'
import { parse as parseUrl } from 'url'
const debug = createDebugger('vite:config')
export interface ConfigEnv {
command: 'build' | 'serve'
mode: string
}
export type UserConfigFn = (env: ConfigEnv) => UserConfig
export type UserConfigExport = 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 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
/**
* 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
/**
* Import aliases
*/
alias?: AliasOptions
/**
* 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?: (Plugin | Plugin[])[]
/**
* CSS related options (preprocessors and CSS modules)
*/
css?: CSSOptions
/**
* Transform options to pass to esbuild.
* Or set to `false` to disable esbuild.
*/
esbuild?: ESBuildOptions | false
/**
* Specify additional files 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
/**
* Dep optimization options
*/
optimizeDeps?: DepOptimizationOptions
/**
* SSR specific options
* @alpha
*/
ssr?: SSROptions
/**
* Force Vite to always resolve listed dependencies to the same copy (from
* project root).
*/
dedupe?: string[]
/**
* Log level.
* Default: 'info'
*/
logLevel?: LogLevel
/**
* Default: true
*/
clearScreen?: boolean
/**
* Base public path when served in development or production.
* @default '/'
*/
base?: string
}
export interface SSROptions {
external?: string[]
noExternal?: string[]
}
export interface InlineConfig extends UserConfig {
configFile?: string | false
}
export type ResolvedConfig = Readonly<
Omit<UserConfig, 'plugins' | 'alias' | 'assetsInclude'> & {
configFile: string | undefined
inlineConfig: UserConfig
root: string
command: 'build' | 'serve'
mode: string
isProduction: boolean
optimizeCacheDir: string | undefined
env: Record<string, any>
alias: Alias[]
plugins: readonly Plugin[]
server: ServerOptions
build: ResolvedBuildOptions
assetsInclude: (file: string) => boolean
logger: Logger
base: string
}
>
export async function resolveConfig(
inlineConfig: InlineConfig,
command: 'build' | 'serve',
defaultMode = 'development'
): Promise<ResolvedConfig> {
let config = inlineConfig
let mode = inlineConfig.mode || defaultMode
const logger = createLogger(config.logLevel, config.clearScreen)
// 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'
}
let { configFile } = config
if (configFile !== false) {
const loadResult = await loadConfigFromFile(
{
mode,
command
},
configFile,
config.root,
config.logLevel
)
if (loadResult) {
config = mergeConfig(loadResult.config, config)
configFile = loadResult.path
}
}
// user config may provide an alternative mode
mode = config.mode || mode
// resolve plugins
const rawUserPlugins = (config.plugins || []).flat().filter((p) => {
return !p.apply || p.apply === command
})
const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(
rawUserPlugins
)
// run config hooks
const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]
userPlugins.forEach((p) => {
if (p.config) {
const res = p.config(config)
if (res) {
config = mergeConfig(config, res)
}
}
})
// resolve root
const resolvedRoot = normalizePath(
config.root ? path.resolve(config.root) : process.cwd()
)
// resolve alias with internal client alias
const resolvedAlias = mergeAlias(
[{ find: /^\/@vite\//, replacement: CLIENT_DIR + '/' }],
config.alias || []
)
// load .env files
const userEnv = loadEnv(mode, resolvedRoot)
// 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
// TODO remove when out of beta
if (config.build?.base) {
logger.warn(
chalk.yellow.bold(
`(!) "build.base" config option is deprecated. ` +
`"base" is now a root-level config option.`
)
)
config.base = config.build.base
}
const BASE_URL = resolveBaseUrl(config.base, command === 'build', logger)
const resolvedBuildOptions = resolveBuildOptions(config.build)
// TODO remove when out of beta
Object.defineProperty(resolvedBuildOptions, 'base', {
get() {
logger.warn(
chalk.yellow.bold(
`(!) "build.base" config option is deprecated. ` +
`"base" is now a root-level config option.\n` +
new Error().stack
)
)
return config.base
}
})
// resolve optimizer cache directory
const pkgPath = lookupFile(
resolvedRoot,
[`package.json`],
true /* pathOnly */
)
const optimizeCacheDir =
pkgPath && path.join(path.dirname(pkgPath), `node_modules/${DEP_CACHE_DIR}`)
const assetsFilter = config.assetsInclude
? createFilter(config.assetsInclude)
: () => false
let hmr = config.server?.hmr === true ? {} : config.server?.hmr
hmr = {
...hmr,
path: BASE_URL !== '/' ? BASE_URL.substr(1) : undefined
}
const server = {
...config.server,
hmr
}
const resolved = {
...config,
configFile: configFile ? normalizePath(configFile) : undefined,
inlineConfig,
root: resolvedRoot,
command,
mode,
isProduction,
optimizeCacheDir,
alias: resolvedAlias,
plugins: userPlugins,
server,
build: resolvedBuildOptions,
env: {
...userEnv,
BASE_URL,
MODE: mode,
DEV: !isProduction,
PROD: isProduction
},
assetsInclude(file: string) {
return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file)
},
logger,
base: BASE_URL
}
resolved.plugins = await resolvePlugins(
resolved,
prePlugins,
normalPlugins,
postPlugins
)
// call configResolved hooks
userPlugins.forEach((p) => {
if (p.configResolved) {
p.configResolved(resolved)
}
})
if (process.env.DEBUG) {
debug(`using resolved config: %O`, {
...resolved,
plugins: resolved.plugins.map((p) => p.name)
})
}
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(
chalk.yellow.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(
chalk.yellow.bold(`(!) "base" option should start with a slash.`)
)
base = '/' + base
}
}
// ensure ending slash
if (!base.endsWith('/')) {
logger.warn(chalk.yellow.bold(`(!) "base" option should end with a slash.`))
base += '/'
}
return base
}
export function mergeConfig(
a: Record<string, any>,
b: Record<string, any>,
isRoot = true
): Record<string, any> {
const merged: Record<string, any> = { ...a }
for (const key in b) {
const value = b[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] = mergeConfig(existing, value, false)
continue
}
// root fields that require special handling
if (existing != null && isRoot) {
if (key === 'alias') {
merged[key] = mergeAlias(existing, value)
continue
} else if (key === 'assetsInclude') {
merged[key] = [].concat(existing, value)
continue
}
}
merged[key] = value
}
return merged
}
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 } | null> {
const start = Date.now()
let resolvedPath: string | undefined
let isTS = false
let isMjs = false
// 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') {
isMjs = true
}
} catch (e) {}
if (configFile) {
// explicit config path is always resolved from cwd
resolvedPath = path.resolve(configFile)
} 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
isMjs = 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
}
resolvedPath = normalizePath(resolvedPath)
try {
let userConfig: UserConfigExport | undefined
if (isMjs) {
if (isTS) {
// before we can register loaders without requiring users to run node
// with --experimental-loader themselves, we have to do a hack here:
// transpile the ts config file with esbuild first, write it to disk,
// load it with native Node ESM, then delete the file.
const src = fs.readFileSync(resolvedPath, 'utf-8')
const { code } = await transformWithEsbuild(src, resolvedPath)
fs.writeFileSync(resolvedPath + '.js', code)
userConfig = (
await eval(`import(resolvedPath + '.js?t=${Date.now()}')`)
).default
fs.unlinkSync(resolvedPath + '.js')
debug(`TS + native esm config loaded in ${Date.now() - start}ms`)
} else {
// using eval 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 eval(`import(resolvedPath + '?t=${Date.now()}')`))
.default
debug(`native esm config loaded in ${Date.now() - start}ms`)
}
}
if (!userConfig && !isTS && !isMjs) {
// 1. try to directly require the module (assuming commonjs)
try {
// clear cache in case of server restart
delete require.cache[require.resolve(resolvedPath)]
userConfig = require(resolvedPath)
debug(`cjs config loaded in ${Date.now() - start}ms`)
} catch (e) {
const ignored = new RegExp(
[
`Cannot use import statement`,
`Unexpected token 'export'`,
`Must use import to load ES Module`,
`Unexpected identifier` // #1635 Node <= 12.4 has no esm detection
].join('|')
)
if (!ignored.test(e.message)) {
throw e
}
}
}
if (!userConfig) {
// 2. if we reach here, the file is ts or using es import syntax, or
// the user has type: "module" in their package.json (#917)
// transpile es import syntax to require syntax using rollup.
// lazy require rollup (it's actually in dependencies)
const code = await bundleConfigFile(resolvedPath)
userConfig = await loadConfigFromBundledFile(resolvedPath, code)
debug(`bundled config file loaded in ${Date.now() - start}ms`)
}
const config =
typeof userConfig === 'function' ? userConfig(configEnv) : userConfig
if (!isObject(config)) {
throw new Error(`config must export or return an object.`)
}
return {
path: resolvedPath,
config
}
} catch (e) {
createLogger(logLevel).error(
chalk.red(`failed to load config from ${resolvedPath}`)
)
throw e
} finally {
await stopService()
}
}
async function bundleConfigFile(fileName: string): Promise<string> {
const rollup = require('rollup') as typeof Rollup
// node-resolve must be imported since it's bundled
const bundle = await rollup.rollup({
external: (id: string) =>
(id[0] !== '.' && !path.isAbsolute(id)) ||
id.slice(-5, id.length) === '.json',
input: fileName,
treeshake: false,
plugins: [
// use esbuild + node-resolve to support .ts files
esbuildPlugin({ target: 'esnext' }),
resolvePlugin({
root: path.dirname(fileName),
isBuild: true,
asSrc: false
}),
{
name: 'replace-import-meta',
transform(code, id) {
return code.replace(
/\bimport\.meta\.url\b/g,
JSON.stringify(`file://${id}`)
)
}
}
]
})
const {
output: [{ code }]
} = await bundle.generate({
exports: 'named',
format: 'cjs'
})
return code
}
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 (normalizePath(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, root: string, prefix = 'VITE_') {
if (mode === 'local') {
throw new Error(
`"local" cannot be used as a mode name because it conflicts with ` +
`the .local postfix for .env files.`
)
}
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 (key.startsWith(prefix) && env[key] === undefined) {
env[key] = process.env[key] as string
}
}
for (const file of envFiles) {
const path = lookupFile(root, [file], true)
if (path) {
const parsed = dotenv.parse(fs.readFileSync(path), {
debug: !!process.env.DEBUG || undefined
})
// let environment variables use each other
dotenvExpand({
parsed,
// prevent process.env mutation
ignoreProcessEnv: true
} as any)
// only keys that start with prefix are exposed to client
for (const [key, value] of Object.entries(parsed)) {
if (key.startsWith(prefix) && env[key] === undefined) {
env[key] = value
} else if (key === 'NODE_ENV') {
// NODE_ENV override in .env file
process.env.VITE_USER_NODE_ENV = value
}
}
}
}
return env
}