Nuxt/packages/cli/src/commands/dev.ts

66 lines
2.0 KiB
TypeScript
Raw Normal View History

import { resolve } from 'upath'
2021-04-15 19:17:44 +00:00
import chokidar from 'chokidar'
import debounce from 'debounce-promise'
import { createServer, createLoadingHandler } from '../utils/server'
import { showBanner } from '../utils/banner'
import { requireModule } from '../utils/cjs'
2021-07-02 12:45:15 +00:00
import { error } from '../utils/log'
2021-04-09 15:52:45 +00:00
export async function invoke (args) {
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
2021-04-09 15:52:45 +00:00
const server = createServer()
2021-07-02 12:45:15 +00:00
const listener = await server.listen({
clipboard: args.clipboard,
open: args.open || args.o
})
2021-04-09 15:52:45 +00:00
2021-04-15 19:17:44 +00:00
const rootDir = resolve(args._[0] || '.')
const { loadNuxt, buildNuxt } = requireModule('@nuxt/kit', rootDir)
let currentNuxt
2021-07-02 12:45:15 +00:00
const load = async (isRestart) => {
2021-04-15 19:17:44 +00:00
try {
2021-07-02 12:45:15 +00:00
const message = `${isRestart ? 'Restarting' : 'Starting'} nuxt...`
server.setApp(createLoadingHandler(message, 1))
if (isRestart) {
console.log(message)
2021-04-15 19:17:44 +00:00
}
2021-07-02 12:45:15 +00:00
if (currentNuxt) {
await currentNuxt.close()
}
const newNuxt = await loadNuxt({ rootDir, dev: true, ready: false })
currentNuxt = newNuxt
2021-04-15 19:17:44 +00:00
await currentNuxt.ready()
await buildNuxt(currentNuxt)
server.setApp(currentNuxt.server.app)
2021-07-02 12:45:15 +00:00
if (isRestart && args.clear !== false) {
showBanner()
listener.showURL()
}
2021-04-15 19:17:44 +00:00
} catch (err) {
2021-07-02 12:45:15 +00:00
error(`Cannot ${isRestart ? 'restart' : 'start'} nuxt: `, err)
2021-04-15 19:17:44 +00:00
server.setApp(createLoadingHandler(
'Error while loading nuxt. Please check console and fix errors.'
))
}
}
// Watch for config changes
// TODO: Watcher service, modules, and requireTree
2021-04-15 19:17:44 +00:00
const dLoad = debounce(load, 250)
const watcher = chokidar.watch([rootDir], { ignoreInitial: true, depth: 1 })
2021-04-15 19:17:44 +00:00
watcher.on('all', (_event, file) => {
if (file.includes('nuxt.config') || file.includes('modules')) {
2021-07-02 12:45:15 +00:00
dLoad(true)
2021-04-15 19:17:44 +00:00
}
})
2021-04-09 15:52:45 +00:00
2021-07-02 12:45:15 +00:00
await load(false)
2021-04-09 15:52:45 +00:00
}
export const meta = {
usage: 'nu dev [rootDir] [--clipboard] [--open, -o]',
2021-04-09 15:52:45 +00:00
description: 'Run nuxt development server'
}