Skip to content

Commit

Permalink
refactor: some small stuff (#4979)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
manniL authored and Sébastien Chopin committed Feb 8, 2019
1 parent 50b1592 commit 69dfd84
Show file tree
Hide file tree
Showing 13 changed files with 153 additions and 134 deletions.
95 changes: 49 additions & 46 deletions packages/builder/src/builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 }) {
Expand Down Expand Up @@ -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'
)

let customIndicator = false
if (!await fsExtra.exists(indicatorPath)) {
indicatorPath = this.nuxt.resolver.resolveAlias(
this.options.loadingIndicator.name
)
if (!this.options.loadingIndicator.name) {
return
}
let indicatorPath = path.resolve(
this.template.dir,
'views/loading',
this.options.loadingIndicator.name + '.html'
)

if (await fsExtra.exists(indicatorPath)) {
customIndicator = true
} else {
indicatorPath = null
}
}
let customIndicator = false
if (!await fsExtra.exists(indicatorPath)) {
indicatorPath = this.nuxt.resolver.resolveAlias(
this.options.loadingIndicator.name
)

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) {
Expand Down
9 changes: 5 additions & 4 deletions packages/cli/src/commands/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
}
}
5 changes: 2 additions & 3 deletions packages/cli/src/commands/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
},

Expand Down
8 changes: 5 additions & 3 deletions packages/cli/src/commands/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
3 changes: 1 addition & 2 deletions packages/cli/src/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`)
}
}
4 changes: 2 additions & 2 deletions packages/generator/src/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
}
Expand Down
26 changes: 15 additions & 11 deletions packages/server/src/middleware/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,23 @@ 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 = {
statusCode: err.statusCode || 500,
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
Expand Down Expand Up @@ -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
Expand Down
30 changes: 19 additions & 11 deletions packages/server/src/middleware/modern.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
5 changes: 2 additions & 3 deletions packages/server/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
3 changes: 1 addition & 2 deletions packages/utils/src/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 16 additions & 16 deletions packages/vue-renderer/src/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.'
)
}
}

Expand Down Expand Up @@ -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
}
Expand All @@ -240,6 +241,7 @@ export default class VueRenderer {
return true
}

// TODO: Remove in Nuxt 3
get isResourcesAvailable() { /* Backward compatibility */
return this.isReady
}
Expand Down Expand Up @@ -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 = {
Expand Down

0 comments on commit 69dfd84

Please sign in to comment.