mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-23 14:15:13 +00:00
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:
parent
50b1592998
commit
69dfd848d7
@ -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,7 +389,10 @@ export default class Builder {
|
||||
|
||||
async resolveStore({ templateVars, templateFiles }) {
|
||||
// Add store if needed
|
||||
if (this.options.store) {
|
||||
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)
|
||||
@ -405,7 +407,6 @@ export default class Builder {
|
||||
|
||||
templateFiles.push('store.js')
|
||||
}
|
||||
}
|
||||
|
||||
async resolveMiddleware({ templateVars }) {
|
||||
// -- Middleware --
|
||||
@ -452,7 +453,9 @@ export default class Builder {
|
||||
}
|
||||
|
||||
async resolveLoadingIndicator({ templateFiles }) {
|
||||
if (this.options.loadingIndicator.name) {
|
||||
if (!this.options.loadingIndicator.name) {
|
||||
return
|
||||
}
|
||||
let indicatorPath = path.resolve(
|
||||
this.template.dir,
|
||||
'views/loading',
|
||||
@ -472,21 +475,21 @@ export default class Builder {
|
||||
}
|
||||
}
|
||||
|
||||
if (indicatorPath) {
|
||||
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
|
||||
})
|
||||
} else {
|
||||
consola.error(
|
||||
`Could not fetch loading indicator: ${
|
||||
this.options.loadingIndicator.name
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async compileTemplates(templateContext) {
|
||||
|
@ -66,10 +66,11 @@ export default {
|
||||
// Build only
|
||||
const builder = await cmd.getBuilder(nuxt)
|
||||
await builder.build()
|
||||
} else {
|
||||
return
|
||||
}
|
||||
|
||||
// Build + Generate for static deployment
|
||||
const generator = await cmd.getGenerator(nuxt)
|
||||
await generator.generate({ build: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
},
|
||||
|
||||
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
@ -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}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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) => {
|
||||
const json = await youch.toJSON()
|
||||
sendResponse(JSON.stringify(json, undefined, 2), 'text/json')
|
||||
})
|
||||
} else {
|
||||
youch.toHTML().then(html => sendResponse(html))
|
||||
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
|
||||
|
@ -25,24 +25,32 @@ const isModernBrowser = (ua) => {
|
||||
|
||||
let detected = false
|
||||
|
||||
const distinctModernModeOptions = [false, 'client', 'server']
|
||||
|
||||
const detectModernBuild = ({ options, resources }) => {
|
||||
if (detected === false && ![false, 'client', 'server'].includes(options.modern)) {
|
||||
if (detected || distinctModernModeOptions.includes(options.modern)) {
|
||||
return
|
||||
}
|
||||
|
||||
detected = true
|
||||
if (resources.modernManifest) {
|
||||
|
||||
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.`)
|
||||
} else {
|
||||
options.modern = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const detectModernBrowser = ({ socket = {}, headers }) => {
|
||||
if (socket.isModernBrowser === undefined) {
|
||||
if (socket.isModernBrowser !== undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
const ua = headers && headers['user-agent']
|
||||
socket.isModernBrowser = isModernBrowser(ua)
|
||||
}
|
||||
}
|
||||
|
||||
const setModernMode = (req, options) => {
|
||||
const { socket = {} } = req
|
||||
|
@ -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') {
|
||||
|
@ -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
|
||||
|
@ -123,24 +123,24 @@ 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) {
|
||||
}
|
||||
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.'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadResources(_fs, isMFS = false) {
|
||||
const distPath = path.resolve(this.context.options.buildDir, 'dist', 'server')
|
||||
@ -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 = {
|
||||
|
@ -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,12 +168,12 @@ 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')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
webpackDev(compiler) {
|
||||
consola.debug('Adding webpack middleware...')
|
||||
@ -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() {
|
||||
|
@ -37,7 +37,9 @@ export default class StyleLoader {
|
||||
const extResource = this.resources[ext]
|
||||
// style-resources-loader
|
||||
// https://github.com/yenshih/style-resources-loader
|
||||
if (extResource) {
|
||||
if (!extResource) {
|
||||
return
|
||||
}
|
||||
const patterns = wrapArray(extResource).map(p => path.resolve(this.rootDir, p))
|
||||
|
||||
return {
|
||||
@ -48,28 +50,35 @@ export default class StyleLoader {
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
postcss() {
|
||||
// postcss-loader
|
||||
// https://github.com/postcss/postcss-loader
|
||||
if (this.postcssConfig) {
|
||||
if (!this.postcssConfig) {
|
||||
return
|
||||
}
|
||||
|
||||
const config = this.postcssConfig.config()
|
||||
if (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) {
|
||||
|
Loading…
Reference in New Issue
Block a user