refactor: some small stuff (#4979)

* refactor: flatten ifs

* refactor: unnecessary curly brackets

* refactor: unnecessary else

* refactor: promise.all instead of for-await

* refactor: apply changes suggested by @clarkdo

* chore: fix typo

* refactor: early return

* refactor: add removal TODOs

* refactor: more descriptive variable name

* refactor: prefer template string

* refactor: one-line

* refactor: early returns

* refactor: early return

* refactor: parallel promises

* refactor: early return and no else

* refactor: spread operator

* refactor: spread operator and early return

* fix: remove error and throw string instead

* fix: always return true

* refactor: clear multiline ternary

* refactor: err stack assignment

* refactor: early return and async/await

* refactor: one line

* refactor: early return

* refactor: early return

* refactor: promise.all

* refactor: args spread
This commit is contained in:
Alexander Lichter 2019-02-08 16:25:11 +00:00 committed by Sébastien Chopin
parent 50b1592998
commit 69dfd848d7
13 changed files with 152 additions and 133 deletions

View File

@ -46,8 +46,7 @@ export default class Builder {
this.supportedExtensions = ['vue', 'js', 'ts', 'tsx'] this.supportedExtensions = ['vue', 'js', 'ts', 'tsx']
// Helper to resolve build paths // Helper to resolve build paths
this.relativeToBuild = (...args) => this.relativeToBuild = (...args) => relativeTo(this.options.buildDir, ...args)
relativeTo(this.options.buildDir, ...args)
this._buildStatus = STATUS.INITIAL this._buildStatus = STATUS.INITIAL
@ -390,21 +389,23 @@ export default class Builder {
async resolveStore({ templateVars, templateFiles }) { async resolveStore({ templateVars, templateFiles }) {
// Add store if needed // Add store if needed
if (this.options.store) { if (!this.options.store) {
templateVars.storeModules = (await this.resolveRelative(this.options.dir.store)) return
.sort(({ src: p1 }, { src: p2 }) => {
// modules are sorted from low to high priority (for overwriting properties)
let res = p1.split('/').length - p2.split('/').length
if (res === 0 && p1.includes('/index.')) {
res = -1
} else if (res === 0 && p2.includes('/index.')) {
res = 1
}
return res
})
templateFiles.push('store.js')
} }
templateVars.storeModules = (await this.resolveRelative(this.options.dir.store))
.sort(({ src: p1 }, { src: p2 }) => {
// modules are sorted from low to high priority (for overwriting properties)
let res = p1.split('/').length - p2.split('/').length
if (res === 0 && p1.includes('/index.')) {
res = -1
} else if (res === 0 && p2.includes('/index.')) {
res = 1
}
return res
})
templateFiles.push('store.js')
} }
async resolveMiddleware({ templateVars }) { async resolveMiddleware({ templateVars }) {
@ -452,41 +453,43 @@ export default class Builder {
} }
async resolveLoadingIndicator({ templateFiles }) { async resolveLoadingIndicator({ templateFiles }) {
if (this.options.loadingIndicator.name) { if (!this.options.loadingIndicator.name) {
let indicatorPath = path.resolve( return
this.template.dir, }
'views/loading', let indicatorPath = path.resolve(
this.options.loadingIndicator.name + '.html' this.template.dir,
'views/loading',
this.options.loadingIndicator.name + '.html'
)
let customIndicator = false
if (!await fsExtra.exists(indicatorPath)) {
indicatorPath = this.nuxt.resolver.resolveAlias(
this.options.loadingIndicator.name
) )
let customIndicator = false if (await fsExtra.exists(indicatorPath)) {
if (!await fsExtra.exists(indicatorPath)) { customIndicator = true
indicatorPath = this.nuxt.resolver.resolveAlias(
this.options.loadingIndicator.name
)
if (await fsExtra.exists(indicatorPath)) {
customIndicator = true
} else {
indicatorPath = null
}
}
if (indicatorPath) {
templateFiles.push({
src: indicatorPath,
dst: 'loading.html',
custom: customIndicator,
options: this.options.loadingIndicator
})
} else { } else {
consola.error( indicatorPath = null
`Could not fetch loading indicator: ${
this.options.loadingIndicator.name
}`
)
} }
} }
if (!indicatorPath) {
consola.error(
`Could not fetch loading indicator: ${
this.options.loadingIndicator.name
}`
)
return
}
templateFiles.push({
src: indicatorPath,
dst: 'loading.html',
custom: customIndicator,
options: this.options.loadingIndicator
})
} }
async compileTemplates(templateContext) { async compileTemplates(templateContext) {

View File

@ -66,10 +66,11 @@ export default {
// Build only // Build only
const builder = await cmd.getBuilder(nuxt) const builder = await cmd.getBuilder(nuxt)
await builder.build() await builder.build()
} else { return
// Build + Generate for static deployment
const generator = await cmd.getGenerator(nuxt)
await generator.generate({ build: true })
} }
// Build + Generate for static deployment
const generator = await cmd.getGenerator(nuxt)
await generator.generate({ build: true })
} }
} }

View File

@ -24,9 +24,8 @@ export default {
// Opens the server listeners url in the default browser // Opens the server listeners url in the default browser
if (argv.open) { if (argv.open) {
for (const listener of nuxt.server.listeners) { const openerPromises = nuxt.server.listeners.map(listener => opener(listener.url))
await opener(listener.url) await Promise.all(openerPromises)
}
} }
}, },

View File

@ -18,10 +18,12 @@ export default {
return listCommands() return listCommands()
} }
const command = await getCommand(name) const command = await getCommand(name)
if (command) {
NuxtCommand.from(command).showHelp() if (!command) {
} else {
consola.info(`Unknown command: ${name}`) consola.info(`Unknown command: ${name}`)
return
} }
NuxtCommand.from(command).showHelp()
} }
} }

View File

@ -35,8 +35,7 @@ export default async function run(_argv) {
} catch (error) { } catch (error) {
if (error.code === 'ENOENT') { if (error.code === 'ENOENT') {
throw String(`Command not found: nuxt-${argv[0]}`) throw String(`Command not found: nuxt-${argv[0]}`)
} else {
throw String(`Failed to run command \`nuxt-${argv[0]}\`:\n${error}`)
} }
throw String(`Failed to run command \`nuxt-${argv[0]}\`:\n${error}`)
} }
} }

View File

@ -210,7 +210,7 @@ export default class Generator {
} }
} catch (err) { } catch (err) {
pageErrors.push({ type: 'unhandled', route, error: err }) pageErrors.push({ type: 'unhandled', route, error: err })
Array.prototype.push.apply(errors, pageErrors) errors.push(...pageErrors)
await this.nuxt.callHook('generate:routeFailed', { await this.nuxt.callHook('generate:routeFailed', {
route, route,
@ -269,7 +269,7 @@ export default class Generator {
if (pageErrors.length) { if (pageErrors.length) {
consola.error('Error generating ' + route) consola.error('Error generating ' + route)
Array.prototype.push.apply(errors, pageErrors) errors.push(...pageErrors)
} else { } else {
consola.success('Generated ' + route) consola.success('Generated ' + route)
} }

View File

@ -4,7 +4,7 @@ import consola from 'consola'
import Youch from '@nuxtjs/youch' import Youch from '@nuxtjs/youch'
export default ({ resources, options }) => function errorMiddleware(err, req, res, next) { export default ({ resources, options }) => async function errorMiddleware(err, req, res, next) {
// ensure statusCode, message and name fields // ensure statusCode, message and name fields
const error = { const error = {
@ -12,11 +12,15 @@ export default ({ resources, options }) => function errorMiddleware(err, req, re
message: err.message || 'Nuxt Server Error', message: err.message || 'Nuxt Server Error',
name: !err.name || err.name === 'Error' ? 'NuxtServerError' : err.name name: !err.name || err.name === 'Error' ? 'NuxtServerError' : err.name
} }
const errorFull = err instanceof Error ? err : typeof err === 'string' const errorFull = err instanceof Error
? new Error(err) : new Error(err.message || JSON.stringify(err)) ? err
if (err.stack) errorFull.stack = err.stack : typeof err === 'string'
? new Error(err)
: new Error(err.message || JSON.stringify(err))
errorFull.name = error.name errorFull.name = error.name
errorFull.statusCode = error.statusCode errorFull.statusCode = error.statusCode
errorFull.stack = err.stack || undefined
const sendResponse = (content, type = 'text/html') => { const sendResponse = (content, type = 'text/html') => {
// Set Headers // Set Headers
@ -71,18 +75,18 @@ export default ({ resources, options }) => function errorMiddleware(err, req, re
true true
) )
if (isJson) { if (isJson) {
youch.toJSON().then((json) => { const json = await youch.toJSON()
sendResponse(JSON.stringify(json, undefined, 2), 'text/json') sendResponse(JSON.stringify(json, undefined, 2), 'text/json')
}) return
} else {
youch.toHTML().then(html => sendResponse(html))
} }
const html = await youch.toHTML()
sendResponse(html)
} }
const readSourceFactory = ({ srcDir, rootDir, buildDir }) => async function readSource(frame) { const readSourceFactory = ({ srcDir, rootDir, buildDir }) => async function readSource(frame) {
// Remove webpack:/// & query string from the end // Remove webpack:/// & query string from the end
const sanitizeName = name => const sanitizeName = name => name ? name.replace('webpack:///', '').split('?')[0] : null
name ? name.replace('webpack:///', '').split('?')[0] : null
frame.fileName = sanitizeName(frame.fileName) frame.fileName = sanitizeName(frame.fileName)
// Return if fileName is unknown // Return if fileName is unknown

View File

@ -25,23 +25,31 @@ const isModernBrowser = (ua) => {
let detected = false let detected = false
const distinctModernModeOptions = [false, 'client', 'server']
const detectModernBuild = ({ options, resources }) => { const detectModernBuild = ({ options, resources }) => {
if (detected === false && ![false, 'client', 'server'].includes(options.modern)) { if (detected || distinctModernModeOptions.includes(options.modern)) {
detected = true return
if (resources.modernManifest) {
options.modern = options.render.ssr ? 'server' : 'client'
consola.info(`Modern bundles are detected. Modern mode (${chalk.green.bold(options.modern)}) is enabled now.`)
} else {
options.modern = false
}
} }
detected = true
if (!resources.modernManifest) {
options.modern = false
return
}
options.modern = options.render.ssr ? 'server' : 'client'
consola.info(`Modern bundles are detected. Modern mode (${chalk.green.bold(options.modern)}) is enabled now.`)
} }
const detectModernBrowser = ({ socket = {}, headers }) => { const detectModernBrowser = ({ socket = {}, headers }) => {
if (socket.isModernBrowser === undefined) { if (socket.isModernBrowser !== undefined) {
const ua = headers && headers['user-agent'] return
socket.isModernBrowser = isModernBrowser(ua)
} }
const ua = headers && headers['user-agent']
socket.isModernBrowser = isModernBrowser(ua)
} }
const setModernMode = (req, options) => { const setModernMode = (req, options) => {

View File

@ -253,9 +253,8 @@ export default class Server {
} }
this.__closed = true this.__closed = true
for (const listener of this.listeners) { await Promise.all(this.listeners.map(l => l.close()))
await listener.close()
}
this.listeners = [] this.listeners = []
if (typeof this.renderer.close === 'function') { if (typeof this.renderer.close === 'function') {

View File

@ -38,8 +38,7 @@ export const r = function r(...args) {
return wp(path.resolve(...args.map(normalize))) return wp(path.resolve(...args.map(normalize)))
} }
export const relativeTo = function relativeTo() { export const relativeTo = function relativeTo(...args) {
const args = Array.prototype.slice.apply(arguments)
const dir = args.shift() const dir = args.shift()
// Keep webpack inline loader intact // Keep webpack inline loader intact

View File

@ -123,22 +123,22 @@ export default class VueRenderer {
// Try once to load SSR resources from fs // Try once to load SSR resources from fs
await this.loadResources(fs) await this.loadResources(fs)
// Without using `nuxt start` (Programatic, Tests and Generate) // Without using `nuxt start` (Programmatic, Tests and Generate)
if (!this.context.options._start) { if (!this.context.options._start) {
this.context.nuxt.hook('build:resources', () => this.loadResources(fs)) this.context.nuxt.hook('build:resources', () => this.loadResources(fs))
return
} }
// Verify resources // Verify resources
if (this.context.options._start) { if (!this.isReady) {
if (!this.isReady) { throw new Error(
throw new Error( 'No build files found. Use either `nuxt build` or `builder.build()` or start nuxt in development mode.'
'No build files found. Use either `nuxt build` or `builder.build()` or start nuxt in development mode.' )
) }
} else if (this.context.options.modern && !this.context.resources.modernManifest) { if (this.context.options.modern && !this.context.resources.modernManifest) {
throw new Error( throw new Error(
'No modern build files found. Use either `nuxt build --modern` or `modern` option to build modern files.' 'No modern build files found. Use either `nuxt build --modern` or `modern` option to build modern files.'
) )
}
} }
} }
@ -218,6 +218,7 @@ export default class VueRenderer {
return this.context.nuxt.callHook('render:resourcesLoaded', this.context.resources) return this.context.nuxt.callHook('render:resourcesLoaded', this.context.resources)
} }
// TODO: Remove in Nuxt 3
get noSSR() { /* Backward compatibility */ get noSSR() { /* Backward compatibility */
return this.context.options.render.ssr === false return this.context.options.render.ssr === false
} }
@ -240,6 +241,7 @@ export default class VueRenderer {
return true return true
} }
// TODO: Remove in Nuxt 3
get isResourcesAvailable() { /* Backward compatibility */ get isResourcesAvailable() { /* Backward compatibility */
return this.isReady return this.isReady
} }
@ -293,17 +295,15 @@ export default class VueRenderer {
opts.head_attrs = opts.HEAD_ATTRS opts.head_attrs = opts.HEAD_ATTRS
opts.body_attrs = opts.BODY_ATTRS opts.body_attrs = opts.BODY_ATTRS
const fn = ssr ? this.context.resources.ssrTemplate : this.context.resources.spaTemplate const templateFn = ssr ? this.context.resources.ssrTemplate : this.context.resources.spaTemplate
return fn(opts) return templateFn(opts)
} }
async renderSPA(context) { async renderSPA(context) {
const content = await this.renderer.spa.render(context) const content = await this.renderer.spa.render(context)
const APP = const APP = `<div id="${this.context.globals.id}">${this.context.resources.loadingHTML}</div>${content.BODY_SCRIPTS}`
`<div id="${this.context.globals.id}">${this.context.resources.loadingHTML}</div>` +
content.BODY_SCRIPTS
// Prepare template params // Prepare template params
const templateParams = { const templateParams = {

View File

@ -117,9 +117,7 @@ export class WebpackBundler {
// Start Builds // Start Builds
const runner = options.dev ? parallel : sequence const runner = options.dev ? parallel : sequence
await runner(this.compilers, (compiler) => { await runner(this.compilers, compiler => this.webpackCompile(compiler))
return this.webpackCompile(compiler)
})
} }
async webpackCompile(compiler) { async webpackCompile(compiler) {
@ -170,10 +168,10 @@ export class WebpackBundler {
if (stats.hasErrors()) { if (stats.hasErrors()) {
if (options.build.quiet === true) { if (options.build.quiet === true) {
return Promise.reject(stats.toString(options.build.stats)) return Promise.reject(stats.toString(options.build.stats))
} else {
// Actual error will be printed by webpack
throw new Error('Nuxt Build Error')
} }
// Actual error will be printed by webpack
throw new Error('Nuxt Build Error')
} }
} }
@ -226,9 +224,7 @@ export class WebpackBundler {
} }
async unwatch() { async unwatch() {
for (const watching of this.compilersWatching) { await Promise.all(this.compilersWatching.map(watching => watching.close()))
await watching.close()
}
} }
async close() { async close() {

View File

@ -37,39 +37,48 @@ export default class StyleLoader {
const extResource = this.resources[ext] const extResource = this.resources[ext]
// style-resources-loader // style-resources-loader
// https://github.com/yenshih/style-resources-loader // https://github.com/yenshih/style-resources-loader
if (extResource) { if (!extResource) {
const patterns = wrapArray(extResource).map(p => path.resolve(this.rootDir, p)) return
}
const patterns = wrapArray(extResource).map(p => path.resolve(this.rootDir, p))
return { return {
loader: 'style-resources-loader', loader: 'style-resources-loader',
options: Object.assign( options: Object.assign(
{ patterns }, { patterns },
this.resources.options || {} this.resources.options || {}
) )
}
} }
} }
postcss() { postcss() {
// postcss-loader // postcss-loader
// https://github.com/postcss/postcss-loader // https://github.com/postcss/postcss-loader
if (this.postcssConfig) { if (!this.postcssConfig) {
const config = this.postcssConfig.config() return
if (config) { }
return {
loader: 'postcss-loader', const config = this.postcssConfig.config()
options: Object.assign({ sourceMap: this.sourceMap }, config)
} if (!config) {
} return
}
return {
loader: 'postcss-loader',
options: Object.assign({ sourceMap: this.sourceMap }, config)
} }
} }
css(options) { css(options) {
options.exportOnlyLocals = this.exportOnlyLocals options.exportOnlyLocals = this.exportOnlyLocals
return [ const cssLoader = { loader: 'css-loader', options }
...options.exportOnlyLocals ? [] : [this.styleLoader()],
{ loader: 'css-loader', options } if (options.exportOnlyLocals) {
] return [cssLoader]
}
return [this.styleLoader(), cssLoader]
} }
cssModules(options) { cssModules(options) {