Watch changes on nuxt.config.js when launching nuxt-dev

This commit is contained in:
Sébastien Chopin 2016-11-16 18:41:09 +01:00
parent d2c0f01593
commit a98e6d4e9b
3 changed files with 41 additions and 3 deletions

View File

@ -3,9 +3,12 @@
// Show logs
process.env.DEBUG = 'nuxt:*'
const _ = require('lodash')
const debug = require('debug')('nuxt:build')
const fs = require('fs')
const Nuxt = require('../')
const Server = require('../lib/server')
const chokidar = require('chokidar')
const { resolve } = require('path')
const rootDir = resolve(process.argv.slice(2)[0] || '.')
@ -22,10 +25,38 @@ options.dev = true // Add hot reloading and watching changes
new Nuxt(options)
.then((nuxt) => {
new Server(nuxt)
const server = new Server(nuxt)
.listen(process.env.PORT, process.env.HOST)
listenOnConfigChanges(nuxt, server)
})
.catch((err) => {
console.error(err)
process.exit(1)
})
function listenOnConfigChanges (nuxt, server) {
// Listen on nuxt.config.js changes
const build = _.debounce(() => {
debug('[nuxt.config.js] changed, rebuilding the app...')
delete require.cache[nuxtConfigFile]
let options = {}
if (fs.existsSync(nuxtConfigFile)) {
options = require(nuxtConfigFile)
}
options.rootDir = rootDir
nuxt.close()
.then(() => {
return new Nuxt(options)
})
.then((nuxt) => {
server.nuxt = nuxt
})
.catch((error) => {
console.error('Error while rebuild the app:', error)
process.exit(1)
})
}, 200)
const nuxtConfigFile = resolve(rootDir, 'nuxt.config.js')
chokidar.watch(nuxtConfigFile, { ignoreInitial: true })
.on('all', build)
}

View File

@ -5,7 +5,13 @@ const http = require('http')
class Server {
constructor (nuxt) {
this.server = http.createServer(nuxt.render.bind(nuxt))
this.nuxt = nuxt
this.server = http.createServer(this.render.bind(this))
return this
}
render (req, res) {
this.nuxt.render(req, res)
return this
}
@ -15,6 +21,7 @@ class Server {
this.server.listen(port, host, () => {
console.log('Ready on http://%s:%s', host, port)
})
return this
}
}

View File

@ -1,6 +1,6 @@
{
"name": "nuxt",
"version": "0.4.2",
"version": "0.4.3",
"description": "A minimalistic framework for server-rendered Vue.js applications (inspired by Next.js)",
"main": "index.js",
"license": "MIT",