This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
dev.ts
163 lines (145 loc) · 6.12 KB
/
dev.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
import type { AddressInfo } from 'node:net'
import { RequestListener } from 'node:http'
import { existsSync, readdirSync } from 'node:fs'
import { resolve, relative, normalize } from 'pathe'
import chokidar from 'chokidar'
import { debounce } from 'perfect-debounce'
import type { Nuxt } from '@nuxt/schema'
import consola from 'consola'
import { withTrailingSlash } from 'ufo'
import { setupDotenv } from 'c12'
import { showBanner, showVersions } from '../utils/banner'
import { writeTypes } from '../utils/prepare'
import { loadKit } from '../utils/kit'
import { importModule } from '../utils/cjs'
import { overrideEnv } from '../utils/env'
import { writeNuxtManifest, loadNuxtManifest, cleanupNuxtDirs } from '../utils/nuxt'
import { defineNuxtCommand } from './index'
export default defineNuxtCommand({
meta: {
name: 'dev',
usage: 'npx nuxi dev [rootDir] [--dotenv] [--clipboard] [--open, -o] [--port, -p] [--host, -h] [--https] [--ssl-cert] [--ssl-key]',
description: 'Run nuxt development server'
},
async invoke (args) {
overrideEnv('development')
const { listen } = await import('listhen')
const { toNodeListener } = await import('h3')
let currentHandler: RequestListener | undefined
let loadingMessage = 'Nuxt is starting...'
const loadingHandler: RequestListener = async (_req, res) => {
const { loading: loadingTemplate } = await importModule('@nuxt/ui-templates')
res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.statusCode = 503 // Service Unavailable
res.end(loadingTemplate({ loading: loadingMessage }))
}
const serverHandler: RequestListener = (req, res) => {
return currentHandler ? currentHandler(req, res) : loadingHandler(req, res)
}
const rootDir = resolve(args._[0] || '.')
showVersions(rootDir)
await setupDotenv({ cwd: rootDir, fileName: args.dotenv })
const listener = await listen(serverHandler, {
showURL: false,
clipboard: args.clipboard,
open: args.open || args.o,
port: args.port || args.p || process.env.NUXT_PORT,
hostname: args.host || args.h || process.env.NUXT_HOST,
https: args.https && {
cert: args['ssl-cert'],
key: args['ssl-key']
}
})
const { loadNuxt, buildNuxt } = await loadKit(rootDir)
let currentNuxt: Nuxt
const showURL = () => {
listener.showURL({
// TODO: Normalize URL with trailing slash within schema
baseURL: withTrailingSlash(currentNuxt?.options.app.baseURL) || '/'
})
}
const load = async (isRestart: boolean, reason?: string) => {
try {
loadingMessage = `${reason ? reason + '. ' : ''}${isRestart ? 'Restarting' : 'Starting'} nuxt...`
currentHandler = undefined
if (isRestart) {
consola.info(loadingMessage)
}
if (currentNuxt) {
await currentNuxt.close()
}
currentNuxt = await loadNuxt({ rootDir, dev: true, ready: false })
if (!isRestart) {
showURL()
}
// Write manifest and also check if we need cache invalidation
if (!isRestart) {
const previousManifest = await loadNuxtManifest(currentNuxt.options.buildDir)
const newManifest = await writeNuxtManifest(currentNuxt)
if (previousManifest && newManifest && previousManifest._hash !== newManifest._hash) {
await cleanupNuxtDirs(currentNuxt.options.rootDir)
}
}
await currentNuxt.ready()
await currentNuxt.hooks.callHook('listen', listener.server, listener)
const address = listener.server.address() as AddressInfo
currentNuxt.options.devServer.url = listener.url
currentNuxt.options.devServer.port = address.port
currentNuxt.options.devServer.host = address.address
currentNuxt.options.devServer.https = listener.https
await Promise.all([
writeTypes(currentNuxt).catch(console.error),
buildNuxt(currentNuxt)
])
currentHandler = toNodeListener(currentNuxt.server.app)
if (isRestart && args.clear !== false) {
showBanner()
showURL()
}
} catch (err) {
consola.error(`Cannot ${isRestart ? 'restart' : 'start'} nuxt: `, err)
currentHandler = undefined
loadingMessage = 'Error while loading nuxt. Please check console and fix errors.'
}
}
// Watch for config changes
// TODO: Watcher service, modules, and requireTree
const dLoad = debounce(load)
const watcher = chokidar.watch([rootDir], { ignoreInitial: true, depth: 1 })
watcher.on('all', (event, _file) => {
if (!currentNuxt) { return }
const file = normalize(_file)
const buildDir = withTrailingSlash(normalize(currentNuxt.options.buildDir))
if (file.startsWith(buildDir)) { return }
const relativePath = relative(rootDir, file)
if (file.match(/(nuxt\.config\.(js|ts|mjs|cjs)|\.nuxtignore|\.env|\.nuxtrc)$/)) {
dLoad(true, `${relativePath} updated`)
}
const isDirChange = ['addDir', 'unlinkDir'].includes(event)
const isFileChange = ['add', 'unlink'].includes(event)
const pagesDir = resolve(currentNuxt.options.srcDir, currentNuxt.options.dir.pages)
const reloadDirs = ['components', 'composables'].map(d => resolve(currentNuxt.options.srcDir, d))
if (isDirChange) {
if (reloadDirs.includes(file)) {
return dLoad(true, `Directory \`${relativePath}/\` ${event === 'addDir' ? 'created' : 'removed'}`)
}
}
if (isFileChange) {
if (file.match(/(app|error|app\.config)\.(js|ts|mjs|jsx|tsx|vue)$/)) {
return dLoad(true, `\`${relativePath}\` ${event === 'add' ? 'created' : 'removed'}`)
}
}
if (file.startsWith(pagesDir)) {
const hasPages = existsSync(pagesDir) ? readdirSync(pagesDir).length > 0 : false
if (currentNuxt && !currentNuxt.options.pages && hasPages) {
return dLoad(true, 'Enabling pages...')
}
if (currentNuxt && currentNuxt.options.pages && !hasPages) {
return dLoad(true, 'Disabling pages...')
}
}
})
await load(false)
return 'wait' as const
}
})