forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.ts
349 lines (330 loc) · 10.3 KB
/
cli.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
import path from 'node:path'
import fs from 'node:fs'
import { performance } from 'node:perf_hooks'
import { cac } from 'cac'
import colors from 'picocolors'
import type { BuildOptions } from './build'
import type { ServerOptions } from './server'
import type { LogLevel } from './logger'
import { createLogger } from './logger'
import { VERSION } from './constants'
import { bindShortcuts } from './shortcuts'
import { resolveConfig } from '.'
const cli = cac('vite')
// global options
interface GlobalCLIOptions {
'--'?: string[]
c?: boolean | string
config?: string
base?: string
l?: LogLevel
logLevel?: LogLevel
clearScreen?: boolean
d?: boolean | string
debug?: boolean | string
f?: string
filter?: string
m?: string
mode?: string
force?: boolean
}
let profileSession = global.__vite_profile_session
let profileCount = 0
export const stopProfiler = (
log: (message: string) => void,
): void | Promise<void> => {
if (!profileSession) return
return new Promise((res, rej) => {
profileSession!.post('Profiler.stop', (err: any, { profile }: any) => {
// Write profile to disk, upload, etc.
if (!err) {
const outPath = path.resolve(
`./vite-profile-${profileCount++}.cpuprofile`,
)
fs.writeFileSync(outPath, JSON.stringify(profile))
log(
colors.yellow(
`CPU profile written to ${colors.white(colors.dim(outPath))}`,
),
)
profileSession = undefined
res()
} else {
rej(err)
}
})
})
}
const filterDuplicateOptions = <T extends object>(options: T) => {
for (const [key, value] of Object.entries(options)) {
if (Array.isArray(value)) {
options[key as keyof T] = value[value.length - 1]
}
}
}
/**
* removing global flags before passing as command specific sub-configs
*/
function cleanOptions<Options extends GlobalCLIOptions>(
options: Options,
): Omit<Options, keyof GlobalCLIOptions> {
const ret = { ...options }
delete ret['--']
delete ret.c
delete ret.config
delete ret.base
delete ret.l
delete ret.logLevel
delete ret.clearScreen
delete ret.d
delete ret.debug
delete ret.f
delete ret.filter
delete ret.m
delete ret.mode
return ret
}
cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('--base <path>', `[string] public base path (default: /)`)
.option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
.option('-d, --debug [feat]', `[string | boolean] show debug logs`)
.option('-f, --filter <filter>', `[string] filter debug logs`)
.option('-m, --mode <mode>', `[string] set env mode`)
// dev
cli
.command('[root]', 'start dev server') // default command
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--cors', `[boolean] enable CORS`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option(
'--force',
`[boolean] force the optimizer to ignore the cache and re-bundle`,
)
.action(async (root: string, options: ServerOptions & GlobalCLIOptions) => {
filterDuplicateOptions(options)
// output structure is preserved even after bundling so require()
// is ok here
const { createServer } = await import('./server')
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
optimizeDeps: { force: options.force },
server: cleanOptions(options),
})
if (!server.httpServer) {
throw new Error('HTTP server not available')
}
await server.listen()
const info = server.config.logger.info
const viteStartTime = global.__vite_start_time ?? false
const startupDurationString = viteStartTime
? colors.dim(
`ready in ${colors.reset(
colors.bold(Math.ceil(performance.now() - viteStartTime)),
)} ms`,
)
: ''
info(
`\n ${colors.green(
`${colors.bold('VITE')} v${VERSION}`,
)} ${startupDurationString}\n`,
{ clear: !server.config.logger.hasWarned },
)
server.printUrls()
bindShortcuts(server, {
print: true,
customShortcuts: [
profileSession && {
key: 'p',
description: 'start/stop the profiler',
async action(server) {
if (profileSession) {
await stopProfiler(server.config.logger.info)
} else {
const inspector = await import('node:inspector').then(
(r) => r.default,
)
await new Promise<void>((res) => {
profileSession = new inspector.Session()
profileSession.connect()
profileSession.post('Profiler.enable', () => {
profileSession!.post('Profiler.start', () => {
server.config.logger.info('Profiler started')
res()
})
})
})
}
},
},
],
})
} catch (e) {
const logger = createLogger(options.logLevel)
logger.error(colors.red(`error when starting dev server:\n${e.stack}`), {
error: e,
})
stopProfiler(logger.info)
process.exit(1)
}
})
// build
cli
.command('build [root]', 'build for production')
.option('--target <target>', `[string] transpile target (default: 'modules')`)
.option('--outDir <dir>', `[string] output directory (default: dist)`)
.option(
'--assetsDir <dir>',
`[string] directory under outDir to place assets in (default: assets)`,
)
.option(
'--assetsInlineLimit <number>',
`[number] static asset base64 inline threshold in bytes (default: 4096)`,
)
.option(
'--ssr [entry]',
`[string] build specified entry for server-side rendering`,
)
.option(
'--sourcemap',
`[boolean] output source maps for build (default: false)`,
)
.option(
'--minify [minifier]',
`[boolean | "terser" | "esbuild"] enable/disable minification, ` +
`or specify minifier to use (default: esbuild)`,
)
.option('--manifest [name]', `[boolean | string] emit build manifest json`)
.option('--ssrManifest [name]', `[boolean | string] emit ssr manifest json`)
.option(
'--force',
`[boolean] force the optimizer to ignore the cache and re-bundle (experimental)`,
)
.option(
'--emptyOutDir',
`[boolean] force empty outDir when it's outside of root`,
)
.option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
.action(async (root: string, options: BuildOptions & GlobalCLIOptions) => {
filterDuplicateOptions(options)
const { build } = await import('./build')
const buildOptions: BuildOptions = cleanOptions(options)
try {
await build({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
optimizeDeps: { force: options.force },
build: buildOptions,
})
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error during build:\n${e.stack}`),
{ error: e },
)
process.exit(1)
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message))
}
})
// optimize
cli
.command('optimize [root]', 'pre-bundle dependencies')
.option(
'--force',
`[boolean] force the optimizer to ignore the cache and re-bundle`,
)
.action(
async (root: string, options: { force?: boolean } & GlobalCLIOptions) => {
filterDuplicateOptions(options)
const { optimizeDeps } = await import('./optimizer')
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
},
'build',
)
await optimizeDeps(config, options.force, true)
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when optimizing deps:\n${e.stack}`),
{ error: e },
)
process.exit(1)
}
},
)
cli
.command('preview [root]', 'locally preview production build')
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--outDir <dir>', `[string] output directory (default: dist)`)
.action(
async (
root: string,
options: {
host?: string | boolean
port?: number
https?: boolean
open?: boolean | string
strictPort?: boolean
outDir?: string
} & GlobalCLIOptions,
) => {
filterDuplicateOptions(options)
const { preview } = await import('./preview')
try {
const server = await preview({
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
mode: options.mode,
build: {
outDir: options.outDir,
},
preview: {
port: options.port,
strictPort: options.strictPort,
host: options.host,
https: options.https,
open: options.open,
},
})
server.printUrls()
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when starting preview server:\n${e.stack}`),
{ error: e },
)
process.exit(1)
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message))
}
},
)
cli.help()
cli.version(VERSION)
cli.parse()