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']
// Helper to resolve build paths
this.relativeToBuild = (...args) =>
relativeTo(this.options.buildDir, ...args)
this.relativeToBuild = (...args) => relativeTo(this.options.buildDir, ...args)
this._buildStatus = STATUS.INITIAL
@ -390,21 +389,23 @@ export default class Builder {
async resolveStore({ templateVars, templateFiles }) {
// Add store if needed
if (this.options.store) {
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')
if (!this.options.store) {
return
}
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 }) {
@ -452,41 +453,43 @@ export default class Builder {
}
async resolveLoadingIndicator({ templateFiles }) {
if (this.options.loadingIndicator.name) {
let indicatorPath = path.resolve(
this.template.dir,
'views/loading',
this.options.loadingIndicator.name + '.html'
if (!this.options.loadingIndicator.name) {
return
}
let indicatorPath = path.resolve(
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)) {
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
})
if (await fsExtra.exists(indicatorPath)) {
customIndicator = true
} else {
consola.error(
`Could not fetch loading indicator: ${
this.options.loadingIndicator.name
}`
)
indicatorPath = null
}
}
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) {

View File

@ -66,10 +66,11 @@ export default {
// Build only
const builder = await cmd.getBuilder(nuxt)
await builder.build()
} else {
// Build + Generate for static deployment
const generator = await cmd.getGenerator(nuxt)
await generator.generate({ build: true })
return
}
// 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
if (argv.open) {
for (const listener of nuxt.server.listeners) {
await opener(listener.url)
}
const openerPromises = nuxt.server.listeners.map(listener => opener(listener.url))
await Promise.all(openerPromises)
}
},

View File

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

View File

@ -35,8 +35,7 @@ export default async function run(_argv) {
} catch (error) {
if (error.code === 'ENOENT') {
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) {
pageErrors.push({ type: 'unhandled', route, error: err })
Array.prototype.push.apply(errors, pageErrors)
errors.push(...pageErrors)
await this.nuxt.callHook('generate:routeFailed', {
route,
@ -269,7 +269,7 @@ export default class Generator {
if (pageErrors.length) {
consola.error('Error generating ' + route)
Array.prototype.push.apply(errors, pageErrors)
errors.push(...pageErrors)
} else {
consola.success('Generated ' + route)
}

View File

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

View File

@ -25,23 +25,31 @@ const isModernBrowser = (ua) => {
let detected = false
const distinctModernModeOptions = [false, 'client', 'server']
const detectModernBuild = ({ options, resources }) => {
if (detected === false && ![false, 'client', 'server'].includes(options.modern)) {
detected = true
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
}
if (detected || distinctModernModeOptions.includes(options.modern)) {
return
}
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 }) => {
if (socket.isModernBrowser === undefined) {
const ua = headers && headers['user-agent']
socket.isModernBrowser = isModernBrowser(ua)
if (socket.isModernBrowser !== undefined) {
return
}
const ua = headers && headers['user-agent']
socket.isModernBrowser = isModernBrowser(ua)
}
const setModernMode = (req, options) => {

View File

@ -253,9 +253,8 @@ export default class Server {
}
this.__closed = true
for (const listener of this.listeners) {
await listener.close()
}
await Promise.all(this.listeners.map(l => l.close()))
this.listeners = []
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)))
}
export const relativeTo = function relativeTo() {
const args = Array.prototype.slice.apply(arguments)
export const relativeTo = function relativeTo(...args) {
const dir = args.shift()
// Keep webpack inline loader intact

View File

@ -123,22 +123,22 @@ export default class VueRenderer {
// Try once to load SSR resources from 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) {
this.context.nuxt.hook('build:resources', () => this.loadResources(fs))
return
}
// Verify resources
if (this.context.options._start) {
if (!this.isReady) {
throw new Error(
'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) {
throw new Error(
'No modern build files found. Use either `nuxt build --modern` or `modern` option to build modern files.'
)
}
if (!this.isReady) {
throw new Error(
'No build files found. Use either `nuxt build` or `builder.build()` or start nuxt in development mode.'
)
}
if (this.context.options.modern && !this.context.resources.modernManifest) {
throw new Error(
'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)
}
// TODO: Remove in Nuxt 3
get noSSR() { /* Backward compatibility */
return this.context.options.render.ssr === false
}
@ -240,6 +241,7 @@ export default class VueRenderer {
return true
}
// TODO: Remove in Nuxt 3
get isResourcesAvailable() { /* Backward compatibility */
return this.isReady
}
@ -293,17 +295,15 @@ export default class VueRenderer {
opts.head_attrs = opts.HEAD_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) {
const content = await this.renderer.spa.render(context)
const APP =
`<div id="${this.context.globals.id}">${this.context.resources.loadingHTML}</div>` +
content.BODY_SCRIPTS
const APP = `<div id="${this.context.globals.id}">${this.context.resources.loadingHTML}</div>${content.BODY_SCRIPTS}`
// Prepare template params
const templateParams = {

View File

@ -117,9 +117,7 @@ export class WebpackBundler {
// Start Builds
const runner = options.dev ? parallel : sequence
await runner(this.compilers, (compiler) => {
return this.webpackCompile(compiler)
})
await runner(this.compilers, compiler => this.webpackCompile(compiler))
}
async webpackCompile(compiler) {
@ -170,10 +168,10 @@ export class WebpackBundler {
if (stats.hasErrors()) {
if (options.build.quiet === true) {
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() {
for (const watching of this.compilersWatching) {
await watching.close()
}
await Promise.all(this.compilersWatching.map(watching => watching.close()))
}
async close() {

View File

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