Refactor cli

Extracted common logic
Improved style consistency
This commit is contained in:
qm3ster 2018-02-07 02:26:40 +02:00
parent 8fcef54a23
commit ad0649925d
No known key found for this signature in database
GPG Key ID: D41763D409EF23A0
6 changed files with 92 additions and 114 deletions

43
bin/common/utils.js Normal file
View File

@ -0,0 +1,43 @@
const { Utils } = require('../..')
const { resolve } = require('path')
const { existsSync } = require('fs')
const getRootDir = argv => resolve(argv._[0] || '.')
const getNuxtConfigFile = argv => resolve(getRootDir(argv), argv['config-file'])
exports.nuxtConfigFile = getNuxtConfigFile
exports.loadNuxtConfig = argv => {
const rootDir = getRootDir(argv)
const nuxtConfigFile = getNuxtConfigFile(argv)
let options = {}
if (existsSync(nuxtConfigFile)) {
delete require.cache[nuxtConfigFile]
options = require(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError('Could not load config file: ' + argv['config-file'])
}
if (typeof options.rootDir !== 'string') {
options.rootDir = rootDir
}
// Nuxt Mode
options.mode =
(argv['spa'] && 'spa') || (argv['universal'] && 'universal') || options.mode
return options
}
exports.getLatestHost = argv => {
const port =
argv.port || process.env.PORT || process.env.npm_package_config_nuxt_port
const host =
argv.hostname ||
process.env.HOST ||
process.env.npm_package_config_nuxt_host
return { port, host }
}

View File

@ -4,9 +4,10 @@
process.env.DEBUG = process.env.DEBUG || 'nuxt:*' process.env.DEBUG = process.env.DEBUG || 'nuxt:*'
const { join } = require('path') const { join } = require('path')
const { name, engines } = require('../package.json')
const semver = require('semver') const semver = require('semver')
const { Utils } = require('..') const { Utils } = require('..')
const { name, engines } = require('../package.json')
// Global error handler // Global error handler
process.on('unhandledRejection', _error => { process.on('unhandledRejection', _error => {
@ -14,7 +15,11 @@ process.on('unhandledRejection', _error => {
}) })
if (!semver.satisfies(process.version, engines.node)) { if (!semver.satisfies(process.version, engines.node)) {
Utils.fatalError(`The engine "node" is incompatible with ${name}. Expected version "${engines.node}".`) Utils.fatalError(
`The engine "node" is incompatible with ${name}. Expected version "${
engines.node
}".`
)
} }
const defaultCommand = 'dev' const defaultCommand = 'dev'

View File

@ -1,13 +1,13 @@
#!/usr/bin/env node #!/usr/bin/env node
/* eslint-disable no-console */ /* eslint-disable no-console */
const fs = require('fs')
const parseArgs = require('minimist') const parseArgs = require('minimist')
const { Nuxt, Builder, Generator, Utils } = require('..')
const resolve = require('path').resolve
const debug = require('debug')('nuxt:build') const debug = require('debug')('nuxt:build')
debug.color = 2 // Force green color debug.color = 2 // Force green color
const { Nuxt, Builder, Generator, Utils } = require('..')
const { loadNuxtConfig } = require('./common/utils')
const argv = parseArgs(process.argv.slice(2), { const argv = parseArgs(process.argv.slice(2), {
alias: { alias: {
h: 'help', h: 'help',
@ -39,26 +39,11 @@ if (argv.help) {
process.exit(0) process.exit(0)
} }
const rootDir = resolve(argv._[0] || '.') const options = loadNuxtConfig(argv)
const nuxtConfigFile = resolve(rootDir, argv['config-file'])
var options = {}
if (fs.existsSync(nuxtConfigFile)) {
options = require(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError(`Could not load config file`, argv['config-file'])
}
if (typeof options.rootDir !== 'string') {
options.rootDir = rootDir
}
// Create production build when calling `nuxt build` // Create production build when calling `nuxt build`
options.dev = false options.dev = false
// Nuxt Mode
options.mode =
(argv['spa'] && 'spa') || (argv['universal'] && 'universal') || options.mode
// Analyze option // Analyze option
options.build = options.build || {} options.build = options.build || {}
if (argv.analyze) { if (argv.analyze) {
@ -86,9 +71,7 @@ if (options.mode !== 'spa') {
.build() .build()
.then(() => debug('Building done')) .then(() => debug('Building done'))
.then(() => close()) .then(() => close())
.catch(err => { .catch(Utils.fatalError)
Utils.fatalError(err)
})
} else { } else {
// -- Build for SPA app -- // -- Build for SPA app --
const s = Date.now() const s = Date.now()

View File

@ -1,16 +1,19 @@
#!/usr/bin/env node #!/usr/bin/env node
/* eslint-disable no-console */ /* eslint-disable no-console */
const _ = require('lodash') const defaultsDeep = require('lodash/defaultsDeep')
const debug = require('debug')('nuxt:build') const debug = require('debug')('nuxt:build')
debug.color = 2 // force green color debug.color = 2 // force green color
const fs = require('fs')
const parseArgs = require('minimist') const parseArgs = require('minimist')
const { Nuxt, Builder, Utils } = require('..')
const chokidar = require('chokidar') const chokidar = require('chokidar')
const path = require('path') const { version } = require('../package.json')
const resolve = path.resolve
const pkg = require(path.join('..', 'package.json')) const { Nuxt, Builder, Utils } = require('..')
const {
loadNuxtConfig,
getLatestHost,
nuxtConfigFile
} = require('./common/utils')
const argv = parseArgs(process.argv.slice(2), { const argv = parseArgs(process.argv.slice(2), {
alias: { alias: {
@ -30,7 +33,7 @@ const argv = parseArgs(process.argv.slice(2), {
}) })
if (argv.version) { if (argv.version) {
console.log(pkg.version) console.log(version)
process.exit(0) process.exit(0)
} }
@ -56,19 +59,18 @@ if (argv.help) {
process.exit(0) process.exit(0)
} }
const rootDir = resolve(argv._[0] || '.')
const nuxtConfigFile = resolve(rootDir, argv['config-file'])
// Load config once for chokidar // Load config once for chokidar
const nuxtConfig = loadNuxtConfig() const nuxtConfig = loadNuxtConfig(argv)
_.defaultsDeep(nuxtConfig, { watchers: { chokidar: { ignoreInitial: true } } }) defaultsDeep(nuxtConfig, { watchers: { chokidar: { ignoreInitial: true } } })
// Start dev // Start dev
let dev = startDev() let dev = startDev()
let needToRestart = false let needToRestart = false
// Start watching for nuxt.config.js changes // Start watching for nuxt.config.js changes
chokidar.watch(nuxtConfigFile, nuxtConfig.watchers.chokidar).on('all', () => { chokidar
.watch(nuxtConfigFile(argv), nuxtConfig.watchers.chokidar)
.on('all', () => {
debug('[nuxt.config.js] changed') debug('[nuxt.config.js] changed')
needToRestart = true needToRestart = true
@ -83,12 +85,7 @@ chokidar.watch(nuxtConfigFile, nuxtConfig.watchers.chokidar).on('all', () => {
function startDev(oldInstance) { function startDev(oldInstance) {
// Get latest environment variables // Get latest environment variables
const port = const { port, host } = getLatestHost(argv)
argv.port || process.env.PORT || process.env.npm_package_config_nuxt_port
const host =
argv.hostname ||
process.env.HOST ||
process.env.npm_package_config_nuxt_host
// Error handler // Error handler
const onError = (err, instance) => { const onError = (err, instance) => {
@ -99,7 +96,7 @@ function startDev(oldInstance) {
// Load options // Load options
let options = {} let options = {}
try { try {
options = loadNuxtConfig() options = loadAndAugmentNuxtConfig()
} catch (err) { } catch (err) {
return onError(err, oldInstance) return onError(err, oldInstance)
} }
@ -111,9 +108,9 @@ function startDev(oldInstance) {
try { try {
nuxt = new Nuxt(options) nuxt = new Nuxt(options)
builder = new Builder(nuxt) builder = new Builder(nuxt)
instance = { nuxt: nuxt, builder: builder } instance = { nuxt, builder }
} catch (err) { } catch (err) {
return onError(err, instance || oldInstance) return onError(err, oldInstance)
} }
return ( return (
@ -142,26 +139,11 @@ function startDev(oldInstance) {
) )
} }
function loadNuxtConfig() { function loadAndAugmentNuxtConfig() {
let options = {} const options = loadNuxtConfig(argv)
if (fs.existsSync(nuxtConfigFile)) {
delete require.cache[nuxtConfigFile]
options = require(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError('Could not load config file: ' + argv['config-file'])
}
if (typeof options.rootDir !== 'string') {
options.rootDir = rootDir
}
// Force development mode for add hot reloading and watching changes // Force development mode for add hot reloading and watching changes
options.dev = true options.dev = true
// Nuxt Mode
options.mode =
(argv['spa'] && 'spa') || (argv['universal'] && 'universal') || options.mode
return options return options
} }

View File

@ -1,12 +1,11 @@
#!/usr/bin/env node #!/usr/bin/env node
/* eslint-disable no-console */ /* eslint-disable no-console */
const fs = require('fs')
const parseArgs = require('minimist') const parseArgs = require('minimist')
const debug = require('debug')('nuxt:generate') const debug = require('debug')('nuxt:generate')
const { Nuxt, Builder, Generator, Utils } = require('..') const { Nuxt, Builder, Generator, Utils } = require('..')
const resolve = require('path').resolve const { loadNuxtConfig } = require('./common/utils')
const argv = parseArgs(process.argv.slice(2), { const argv = parseArgs(process.argv.slice(2), {
alias: { alias: {
@ -39,24 +38,10 @@ if (argv.help) {
process.exit(0) process.exit(0)
} }
const rootDir = resolve(argv._[0] || '.') const options = loadNuxtConfig(argv)
const nuxtConfigFile = resolve(rootDir, argv['config-file'])
var options = {}
if (fs.existsSync(nuxtConfigFile)) {
options = require(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError('Could not load config file: ' + argv['config-file'])
}
if (typeof options.rootDir !== 'string') {
options.rootDir = rootDir
}
options.dev = false // Force production mode (no webpack middleware called) options.dev = false // Force production mode (no webpack middleware called)
// Nuxt Mode
options.mode =
(argv['spa'] && 'spa') || (argv['universal'] && 'universal') || options.mode
debug('Generating...') debug('Generating...')
const nuxt = new Nuxt(options) const nuxt = new Nuxt(options)
const builder = new Builder(nuxt) const builder = new Builder(nuxt)
@ -97,6 +82,4 @@ generator
debug('Generate done') debug('Generate done')
process.exit(0) process.exit(0)
}) })
.catch(err => { .catch(Utils.fatalError)
Utils.fatalError(err)
})

View File

@ -3,9 +3,11 @@
const fs = require('fs') const fs = require('fs')
const parseArgs = require('minimist') const parseArgs = require('minimist')
const { Nuxt, Utils } = require('..')
const { resolve } = require('path') const { resolve } = require('path')
const { Nuxt, Utils } = require('..')
const { loadNuxtConfig, getLatestHost } = require('./common/utils')
const argv = parseArgs(process.argv.slice(2), { const argv = parseArgs(process.argv.slice(2), {
alias: { alias: {
h: 'help', h: 'help',
@ -44,28 +46,11 @@ if (argv.help) {
process.exit(0) process.exit(0)
} }
const rootDir = resolve(argv._[0] || '.') const options = loadNuxtConfig(argv)
const nuxtConfigFile = resolve(rootDir, argv['config-file'])
let options = {}
if (fs.existsSync(nuxtConfigFile)) {
options = require(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError('Could not load config file: ' + argv['config-file'])
}
if (typeof options.rootDir !== 'string') {
options.rootDir = rootDir
}
// Force production mode (no webpack middleware called) // Force production mode (no webpack middleware called)
options.dev = false options.dev = false
// Nuxt Mode
options.mode =
(argv['spa'] && 'spa') || (argv['universal'] && 'universal') || options.mode
const nuxt = new Nuxt(options) const nuxt = new Nuxt(options)
// Setup hooks // Setup hooks
@ -93,9 +78,6 @@ if (nuxt.options.render.ssr === true) {
} }
} }
const port = const { port, host } = getLatestHost(argv)
argv.port || process.env.PORT || process.env.npm_package_config_nuxt_port
const host =
argv.hostname || process.env.HOST || process.env.npm_package_config_nuxt_host
nuxt.listen(port, host) nuxt.listen(port, host)