-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathpreview.ts
More file actions
173 lines (155 loc) · 4.72 KB
/
Copy pathpreview.ts
File metadata and controls
173 lines (155 loc) · 4.72 KB
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
import { existsSync, promises as fsp } from 'node:fs'
import { dirname } from 'node:path'
import process from 'node:process'
import { box, outro } from '@clack/prompts'
import { setupDotenv } from 'c12'
import { defineCommand } from 'citty'
import { colors } from 'consola/utils'
import { join, resolve } from 'pathe'
import { x } from 'tinyexec'
import { loadKit } from '../utils/kit'
import { logger } from '../utils/logger'
import { relativeToProcess } from '../utils/paths'
import {
cwdArgs,
dotEnvArgs,
envNameArgs,
extendsArgs,
legacyRootDirArgs,
logLevelArgs,
} from './_shared'
const command = defineCommand({
meta: {
name: 'preview',
description: 'Launches Nitro server for local testing after `nuxi build`.',
},
args: {
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs,
port: {
type: 'string',
description: 'Port to listen on',
alias: ['p'],
},
...dotEnvArgs,
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || 'production'
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir)
const { loadNuxt } = await loadKit(cwd)
const resolvedOutputDir = await new Promise<string>((res) => {
loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv,
},
envName: ctx.args.envName, // c12 will fall back to NODE_ENV
ready: true,
overrides: {
...(ctx.args.extends && { extends: ctx.args.extends }),
modules: [
function (_, nuxt) {
nuxt.hook('nitro:init', (nitro) => {
res(
resolve(
nuxt.options.srcDir || cwd,
nitro.options.output.dir || '.output',
'nitro.json',
),
)
})
},
],
},
})
.then(nuxt => nuxt.close())
.catch(() => '')
})
const defaultOutput = resolve(cwd, '.output', 'nitro.json') // for backwards compatibility
const nitroJSONPaths = [resolvedOutputDir, defaultOutput].filter(Boolean)
const nitroJSONPath = nitroJSONPaths.find(p => existsSync(p))
if (!nitroJSONPath) {
logger.error(
`Cannot find ${colors.cyan('nitro.json')}. Did you run ${colors.cyan('nuxi build')} first? Search path:\n${nitroJSONPaths.join('\n')}`,
)
process.exit(1)
}
const outputPath = dirname(nitroJSONPath)
const nitroJSON = JSON.parse(await fsp.readFile(nitroJSONPath, 'utf-8'))
if (!nitroJSON.commands.preview) {
logger.error('Preview is not supported for this build.')
process.exit(1)
}
const info = [
['Node.js:', `v${process.versions.node}`],
['Nitro preset:', nitroJSON.preset],
['Working directory:', relativeToProcess(cwd)],
] as const
const _infoKeyLen = Math.max(...info.map(([label]) => label.length))
logger.message('')
box(
[
'',
'You are previewing a Nuxt app. In production, do not use this CLI. ',
`Instead, run ${colors.cyan(nitroJSON.commands.preview)} directly.`,
'',
...info.map(
([label, value]) =>
`${label.padEnd(_infoKeyLen, ' ')} ${colors.cyan(value)}`,
),
'',
].join('\n'),
colors.yellow(' Previewing Nuxt app '),
{
contentAlign: 'left',
titleAlign: 'left',
width: 'auto',
titlePadding: 2,
contentPadding: 2,
rounded: true,
withGuide: true,
formatBorder: (text: string) => colors.yellow(text),
},
)
const envFileName = ctx.args.dotenv || '.env'
const envExists = existsSync(resolve(cwd, envFileName))
if (envExists) {
logger.info(
`Loading ${colors.cyan(envFileName)}. This will not be loaded when running the server in production.`,
)
await setupDotenv({ cwd, fileName: envFileName })
}
else if (ctx.args.dotenv) {
logger.error(`Cannot find ${colors.cyan(envFileName)}.`)
}
const port
= ctx.args.port
?? process.env.NUXT_PORT
?? process.env.NITRO_PORT
?? process.env.PORT
outro(
`Running ${colors.cyan(nitroJSON.commands.preview)} in ${colors.cyan(relativeToProcess(cwd))}`,
)
const [cmd, ...cmdArgs] = nitroJSON.commands.preview.split(' ')
const resolvedCmdArgs = cmdArgs.map((arg: string) =>
existsSync(join(outputPath, arg)) ? join(outputPath, arg) : arg,
)
await x(cmd, resolvedCmdArgs, {
throwOnError: true,
nodeOptions: {
stdio: 'inherit',
cwd,
env: {
...process.env,
NUXT_PORT: port,
NITRO_PORT: port,
},
},
})
},
})
export default command