MCPcopy
hub / github.com/vitejs/vite / serve

Function serve

playground/cli-module/__tests__/serve.ts:18–114  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

16export const port = ports['cli-module']
17
18export async function serve() {
19 // collect stdout and stderr streams from child processes here to avoid interfering with regular vitest output
20 const streams = {
21 build: { out: [], err: [] },
22 server: { out: [], err: [] },
23 }
24 // helpers to collect streams
25 const collectStreams = (name, process) => {
26 process.stdout.on('data', (d) => streams[name].out.push(d.toString()))
27 process.stderr.on('data', (d) => streams[name].err.push(d.toString()))
28 }
29 const collectErrorStreams = (name, e) => {
30 e.stdout && streams[name].out.push(e.stdout)
31 e.stderr && streams[name].err.push(e.stderr)
32 }
33
34 // helper to output stream content on error
35 const printStreamsToConsole = async (name) => {
36 const std = streams[name]
37 if (std.out && std.out.length > 0) {
38 console.log(`stdout of ${name}\n${std.out.join('\n')}\n`)
39 }
40 if (std.err && std.err.length > 0) {
41 console.log(`stderr of ${name}\n${std.err.join('\n')}\n`)
42 }
43 }
44
45 // only run `vite build` when needed
46 if (isBuild) {
47 const buildCommand = `${viteBinPath} build`
48 try {
49 const buildProcess = execaCommand(buildCommand, {
50 cwd: rootDir,
51 stdio: 'pipe',
52 })
53 collectStreams('build', buildProcess)
54 await buildProcess
55 } catch (e) {
56 console.error(`error while executing cli command "${buildCommand}":`, e)
57 collectErrorStreams('build', e)
58 await printStreamsToConsole('build')
59 throw e
60 }
61 }
62
63 await kill(port)
64
65 // run `vite --port x` or `vite preview --port x` to start server
66 const viteServerArgs = ['--port', `${port}`, '--strict-port']
67 if (isBuild) {
68 viteServerArgs.unshift('preview')
69 }
70 const serverCommand = `${viteBinPath} ${viteServerArgs.join(' ')}`
71 const serverProcess = execaCommand(serverCommand, {
72 cwd: rootDir,
73 stdio: 'pipe',
74 forceKillAfterDelay: 3000,
75 })

Callers

nothing calls this directly

Calls 6

collectStreamsFunction · 0.70
collectErrorStreamsFunction · 0.70
printStreamsToConsoleFunction · 0.70
startedOnPortFunction · 0.70
closeFunction · 0.70
errorMethod · 0.65

Tested by

no test coverage detected