forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ts
622 lines (588 loc) · 16.2 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
import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import dotenv, { DotenvParseOutput } from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue'
import {
CompilerOptions,
SFCStyleCompileOptions,
SFCAsyncStyleCompileOptions,
SFCTemplateCompileOptions
} from '@vue/compiler-sfc'
import Rollup, {
InputOptions as RollupInputOptions,
OutputOptions as RollupOutputOptions,
OutputChunk
} from 'rollup'
import { createEsbuildPlugin } from './build/buildPluginEsbuild'
import { ServerPlugin } from './server'
import { Resolver, supportedExts } from './resolver'
import { Transform, CustomBlockTransform } from './transform'
import { DepOptimizationOptions } from './optimizer'
import { IKoaProxiesOptions } from 'koa-proxies'
import { ServerOptions } from 'https'
import { lookupFile } from './utils'
export type PreprocessLang = NonNullable<
SFCStyleCompileOptions['preprocessLang']
>
export type PreprocessOptions = SFCStyleCompileOptions['preprocessOptions']
export type CssPreprocessOptions = Record<PreprocessLang, PreprocessOptions>
export { Resolver, Transform }
/**
* Options shared between server and build.
*/
export interface SharedConfig {
/**
* 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
/**
* Import alias. The entries can either be exact request -> request mappings
* (exact, no wildcard syntax), or request path -> fs directory mappings.
* When using directory mappings, the key **must start and end with a slash**.
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* alias: {
* // alias package names
* 'react': '@pika/react',
* 'react-dom': '@pika/react-dom'
*
* // alias a path to a fs directory
* // the key must start and end with a slash
* '/@foo/': path.resolve(__dirname, 'some-special-dir')
* }
* }
* ```
*/
alias?: Record<string, string>
/**
* Custom file transforms.
*/
transforms?: Transform[]
/**
* Define global variable replacements.
* Entries will be defined on `window` during dev and replaced during build.
*/
define?: Record<string, any>
/**
* Resolvers to map dev server public path requests to/from file system paths,
* and optionally map module ids to public path requests.
*/
resolvers?: Resolver[]
/**
* Configure dep optimization behavior.
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* optimizeDeps: {
* exclude: ['dep-a', 'dep-b']
* }
* }
* ```
*/
optimizeDeps?: DepOptimizationOptions
/**
* Options to pass to `@vue/compiler-dom`
*
* https://github.com/vuejs/vue-next/blob/master/packages/compiler-core/src/options.ts
*/
vueCompilerOptions?: CompilerOptions
/**
* Configure what tags/attributes to trasnform into asset url imports,
* or disable the transform altogether with `false`.
*/
vueTransformAssetUrls?: SFCTemplateCompileOptions['transformAssetUrls']
/**
* The options for template block preprocessor render.
*/
vueTemplatePreprocessOptions?: Record<
string,
SFCTemplateCompileOptions['preprocessOptions']
>
/**
* Transform functions for Vue custom blocks.
*
* Example `vue.config.js`:
* ``` js
* module.exports = {
* vueCustomBlockTransforms: {
* i18n: src => `export default Comp => { ... }`
* }
* }
* ```
*/
vueCustomBlockTransforms?: Record<string, CustomBlockTransform>
/**
* Configure what to use for jsx factory and fragment.
* @default 'vue'
*/
jsx?:
| 'vue'
| 'preact'
| 'react'
| {
factory?: string
fragment?: string
}
/**
* Environment mode
*/
mode?: string
/**
* CSS preprocess options
*/
cssPreprocessOptions?: CssPreprocessOptions
/**
* CSS modules options
*/
cssModuleOptions?: SFCAsyncStyleCompileOptions['modulesOptions']
/**
* Enable esbuild
* @default true
*/
enableEsbuild?: boolean
/**
* Environment variables parsed from .env files
* only ones starting with VITE_ are exposed on `import.meta.env`
* @internal
*/
env?: DotenvParseOutput
}
export interface ServerConfig extends SharedConfig {
hostname?: string
port?: number
open?: boolean
/**
* Configure https.
*/
https?: boolean
httpsOptions?: ServerOptions
/**
* Configure custom proxy rules for the dev server. Uses
* [`koa-proxies`](https://github.com/vagusX/koa-proxies) which in turn uses
* [`http-proxy`](https://github.com/http-party/node-http-proxy). Each key can
* be a path Full options
* [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | IKoaProxiesOptions>
/**
* Whether to use a Service Worker to cache served code. This can greatly
* improve full page reload performance, but requires a Service Worker
* update + reload on each server restart.
*
* @default false
*/
serviceWorker?: boolean
configureServer?: ServerPlugin | ServerPlugin[]
}
export interface BuildConfig extends SharedConfig {
/**
* Base public path when served in production.
* @default '/'
*/
base?: string
/**
* Directory relative from `root` where build output will be placed. If the
* directory exists, it will be removed before the build.
* @default 'dist'
*/
outDir?: string
/**
* Directory relative from `outDir` where the built js/css/image assets will
* be placed.
* @default '_assets'
*/
assetsDir?: string
/**
* Static asset files smaller than this number (in bytes) will be inlined as
* base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit?: number
/**
* Whether to code-split CSS. When enabled, CSS in async chunks will be
* inlined as strings in the chunk and inserted via dynamically created
* style tags when the chunk is loaded.
* @default true
*/
cssCodeSplit?: boolean
/**
* Whether to generate sourcemap
* @default false
*/
sourcemap?: boolean
/**
* Set to `false` to dsiable minification, or specify the minifier to use.
* Available options are 'terser' or 'esbuild'.
* @default 'terser'
*/
minify?: boolean | 'terser' | 'esbuild'
/**
* Transpile target for esbuild.
* Defaults to 'es2019' which transpiles optional chaining so it works with
* terser.
* @default 'es2019'
*/
esbuildTarget?: string
/**
* Build for server-side rendering, only as a CLI flag
* for programmatic usage, use `ssrBuild` directly.
* @internal
*/
ssr?: boolean
// The following are API / config only and not documented in the CLI. --------
/**
* Will be passed to rollup.rollup()
*
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupInputOptions?: RollupInputOptions
/**
* Will be passed to bundle.generate()
*
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupOutputOptions?: RollupOutputOptions
/**
* Will be passed to rollup-plugin-vue
*
* https://github.com/vuejs/rollup-plugin-vue/blob/next/src/index.ts
*/
rollupPluginVueOptions?: Partial<RollupPluginVueOptions>
/**
* Will be passed to @rollup/plugin-node-resolve
* https://github.com/rollup/plugins/tree/master/packages/node-resolve#dedupe
*/
rollupDedupe?: string[]
/**
* Whether to log asset info to console
* @default false
*/
silent?: boolean
/**
* Whether to write bundle to disk
* @default true
*/
write?: boolean
/**
* Whether to emit index.html
* @default true
*/
emitIndex?: boolean
/**
* Whether to emit assets other than JavaScript
* @default true
*/
emitAssets?: boolean
/**
* Predicate function that determines whether a link rel=modulepreload shall be
* added to the index.html for the chunk passed in
*/
shouldPreload?: (chunk: OutputChunk) => boolean
/**
* Enable 'rollup-plugin-vue'
* @default true
*/
enableRollupPluginVue?: boolean
}
export interface UserConfig extends BuildConfig, ServerConfig {
plugins?: Plugin[]
}
export interface Plugin
extends Pick<
UserConfig,
| 'alias'
| 'transforms'
| 'define'
| 'resolvers'
| 'configureServer'
| 'vueCompilerOptions'
| 'vueTransformAssetUrls'
| 'vueTemplatePreprocessOptions'
| 'vueCustomBlockTransforms'
| 'rollupInputOptions'
| 'rollupOutputOptions'
| 'enableRollupPluginVue'
> {}
export type ResolvedConfig = UserConfig & {
/**
* Path of config file.
*/
__path?: string
}
const debug = require('debug')('vite:config')
export async function resolveConfig(
mode: string,
configPath?: string
): Promise<ResolvedConfig | undefined> {
const start = Date.now()
const cwd = process.cwd()
let config: ResolvedConfig | undefined
let resolvedPath: string | undefined
let isTS = false
if (configPath) {
resolvedPath = path.resolve(cwd, configPath)
} else {
const jsConfigPath = path.resolve(cwd, 'vite.config.js')
if (fs.existsSync(jsConfigPath)) {
resolvedPath = jsConfigPath
} else {
const tsConfigPath = path.resolve(cwd, 'vite.config.ts')
if (fs.existsSync(tsConfigPath)) {
isTS = true
resolvedPath = tsConfigPath
}
}
}
if (!resolvedPath) {
// load environment variables
return {
env: loadEnv(mode, cwd)
}
}
try {
if (!isTS) {
try {
config = require(resolvedPath)
} catch (e) {
if (
!/Cannot use import statement|Unexpected token 'export'/.test(
e.message
)
) {
throw e
}
}
}
if (!config) {
// 2. if we reach here, the file is ts or using es import syntax.
// transpile es import syntax to require syntax using rollup.
const rollup = require('rollup') as typeof Rollup
const esbuildPlugin = await createEsbuildPlugin({})
// use node-resolve to support .ts files
const nodeResolve = require('@rollup/plugin-node-resolve').nodeResolve({
extensions: supportedExts
})
const bundle = await rollup.rollup({
external: (id: string) =>
(id[0] !== '.' && !path.isAbsolute(id)) ||
id.slice(-5, id.length) === '.json',
input: resolvedPath,
treeshake: false,
plugins: [esbuildPlugin, nodeResolve]
})
const {
output: [{ code }]
} = await bundle.generate({
exports: 'named',
format: 'cjs'
})
config = await loadConfigFromBundledFile(resolvedPath, code)
}
// normalize config root to absolute
if (config.root && !path.isAbsolute(config.root)) {
config.root = path.resolve(path.dirname(resolvedPath), config.root)
}
// resolve plugins
if (config.plugins) {
for (const plugin of config.plugins) {
config = resolvePlugin(config, plugin)
}
}
config.env = {
...config.env,
...loadEnv(mode, config.root || cwd)
}
debug(`config resolved in ${Date.now() - start}ms`)
config.__path = resolvedPath
return config
} catch (e) {
console.error(
chalk.red(`[vite] failed to load config from ${resolvedPath}:`)
)
console.error(e)
process.exit(1)
}
}
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)
}
}
delete require.cache[fileName]
const raw = require(fileName)
const config = raw.__esModule ? raw.default : raw
require.extensions[extension] = defaultLoader
return config
}
function resolvePlugin(config: UserConfig, plugin: Plugin): UserConfig {
return {
...config,
...plugin,
alias: {
...plugin.alias,
...config.alias
},
define: {
...plugin.define,
...config.define
},
transforms: [...(config.transforms || []), ...(plugin.transforms || [])],
resolvers: [...(config.resolvers || []), ...(plugin.resolvers || [])],
configureServer: ([] as any[]).concat(
config.configureServer || [],
plugin.configureServer || []
),
vueCompilerOptions: {
...config.vueCompilerOptions,
...plugin.vueCompilerOptions
},
vueTransformAssetUrls: mergeAssetUrlOptions(
config.vueTransformAssetUrls,
plugin.vueTransformAssetUrls
),
vueTemplatePreprocessOptions: {
...config.vueTemplatePreprocessOptions,
...plugin.vueTemplatePreprocessOptions
},
vueCustomBlockTransforms: {
...config.vueCustomBlockTransforms,
...plugin.vueCustomBlockTransforms
},
rollupInputOptions: mergeObjectOptions(
config.rollupInputOptions,
plugin.rollupInputOptions
),
rollupOutputOptions: mergeObjectOptions(
config.rollupOutputOptions,
plugin.rollupOutputOptions
),
enableRollupPluginVue:
config.enableRollupPluginVue || plugin.enableRollupPluginVue
}
}
function mergeAssetUrlOptions(
to: SFCTemplateCompileOptions['transformAssetUrls'],
from: SFCTemplateCompileOptions['transformAssetUrls']
): SFCTemplateCompileOptions['transformAssetUrls'] {
if (from === true) {
return to
}
if (from === false) {
return from
}
if (typeof to === 'boolean') {
return from || to
}
return {
...normalizeAssetUrlOptions(to),
...normalizeAssetUrlOptions(from)
}
}
function normalizeAssetUrlOptions(o: Record<string, any> | undefined) {
if (o && Object.keys(o).some((key) => Array.isArray(o[key]))) {
return {
tags: o
}
} else {
return o
}
}
function mergeObjectOptions(to: any, from: any) {
if (!to) return from
if (!from) return to
const res: any = { ...to }
for (const key in from) {
const existing = res[key]
const toMerge = from[key]
if (Array.isArray(existing) || Array.isArray(toMerge)) {
res[key] = [].concat(existing, toMerge).filter(Boolean)
} else {
res[key] = toMerge
}
}
return res
}
function loadEnv(mode: string, root: string): 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.`
)
}
debug(`env mode: ${mode}`)
const nodeEnv = process.env
const clientEnv: Record<string, string> = {}
const envFiles = [
/** mode local file */ `.env.${mode}.local`,
/** mode file */ `.env.${mode}`,
/** local file */ `.env.local`,
/** default file */ `.env`
]
for (const file of envFiles) {
const path = lookupFile(root, [file], true)
if (path) {
const result = dotenv.config({
debug: !!process.env.DEBUG || undefined,
path
})
if (result.error) {
throw result.error
}
dotenvExpand(result)
for (const key in result.parsed) {
const value = (nodeEnv[key] = result.parsed![key])
// only keys that start with VITE_ are exposed.
if (key.startsWith(`VITE_`)) {
clientEnv[key] = value
}
// set NODE_ENV under a different key so that we know this is set from
// vite-loaded .env files. Some users may have default NODE_ENV set in
// their system.
if (key === 'NODE_ENV') {
nodeEnv.VITE_ENV = value
}
}
}
}
debug(`env: %O`, clientEnv)
return clientEnv
}
// TODO move this into Vue plugin when we extract it
export const defaultDefines = {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false
}