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']
|
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,7 +389,10 @@ 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) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
templateVars.storeModules = (await this.resolveRelative(this.options.dir.store))
|
templateVars.storeModules = (await this.resolveRelative(this.options.dir.store))
|
||||||
.sort(({ src: p1 }, { src: p2 }) => {
|
.sort(({ src: p1 }, { src: p2 }) => {
|
||||||
// modules are sorted from low to high priority (for overwriting properties)
|
// modules are sorted from low to high priority (for overwriting properties)
|
||||||
@ -405,7 +407,6 @@ export default class Builder {
|
|||||||
|
|
||||||
templateFiles.push('store.js')
|
templateFiles.push('store.js')
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
async resolveMiddleware({ templateVars }) {
|
async resolveMiddleware({ templateVars }) {
|
||||||
// -- Middleware --
|
// -- Middleware --
|
||||||
@ -452,7 +453,9 @@ export default class Builder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async resolveLoadingIndicator({ templateFiles }) {
|
async resolveLoadingIndicator({ templateFiles }) {
|
||||||
if (this.options.loadingIndicator.name) {
|
if (!this.options.loadingIndicator.name) {
|
||||||
|
return
|
||||||
|
}
|
||||||
let indicatorPath = path.resolve(
|
let indicatorPath = path.resolve(
|
||||||
this.template.dir,
|
this.template.dir,
|
||||||
'views/loading',
|
'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({
|
templateFiles.push({
|
||||||
src: indicatorPath,
|
src: indicatorPath,
|
||||||
dst: 'loading.html',
|
dst: 'loading.html',
|
||||||
custom: customIndicator,
|
custom: customIndicator,
|
||||||
options: this.options.loadingIndicator
|
options: this.options.loadingIndicator
|
||||||
})
|
})
|
||||||
} else {
|
|
||||||
consola.error(
|
|
||||||
`Could not fetch loading indicator: ${
|
|
||||||
this.options.loadingIndicator.name
|
|
||||||
}`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async compileTemplates(templateContext) {
|
async compileTemplates(templateContext) {
|
||||||
|
@ -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
|
// Build + Generate for static deployment
|
||||||
const generator = await cmd.getGenerator(nuxt)
|
const generator = await cmd.getGenerator(nuxt)
|
||||||
await generator.generate({ build: true })
|
await generator.generate({ build: true })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
@ -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)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
@ -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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
@ -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)
|
||||||
}
|
}
|
||||||
|
@ -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
|
||||||
|
@ -25,24 +25,32 @@ 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)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
detected = true
|
detected = true
|
||||||
if (resources.modernManifest) {
|
|
||||||
|
if (!resources.modernManifest) {
|
||||||
|
options.modern = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
options.modern = options.render.ssr ? 'server' : 'client'
|
options.modern = options.render.ssr ? 'server' : 'client'
|
||||||
consola.info(`Modern bundles are detected. Modern mode (${chalk.green.bold(options.modern)}) is enabled now.`)
|
consola.info(`Modern bundles are detected. Modern mode (${chalk.green.bold(options.modern)}) is enabled now.`)
|
||||||
} else {
|
|
||||||
options.modern = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const detectModernBrowser = ({ socket = {}, headers }) => {
|
const detectModernBrowser = ({ socket = {}, headers }) => {
|
||||||
if (socket.isModernBrowser === undefined) {
|
if (socket.isModernBrowser !== undefined) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const ua = headers && headers['user-agent']
|
const ua = headers && headers['user-agent']
|
||||||
socket.isModernBrowser = isModernBrowser(ua)
|
socket.isModernBrowser = isModernBrowser(ua)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const setModernMode = (req, options) => {
|
const setModernMode = (req, options) => {
|
||||||
const { socket = {} } = req
|
const { socket = {} } = req
|
||||||
|
@ -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') {
|
||||||
|
@ -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
|
||||||
|
@ -123,24 +123,24 @@ 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.'
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
loadResources(_fs, isMFS = false) {
|
loadResources(_fs, isMFS = false) {
|
||||||
const distPath = path.resolve(this.context.options.buildDir, 'dist', 'server')
|
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)
|
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 = {
|
||||||
|
@ -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,12 +168,12 @@ 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
|
// Actual error will be printed by webpack
|
||||||
throw new Error('Nuxt Build Error')
|
throw new Error('Nuxt Build Error')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
webpackDev(compiler) {
|
webpackDev(compiler) {
|
||||||
consola.debug('Adding webpack middleware...')
|
consola.debug('Adding webpack middleware...')
|
||||||
@ -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() {
|
||||||
|
@ -37,7 +37,9 @@ 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) {
|
||||||
|
return
|
||||||
|
}
|
||||||
const patterns = wrapArray(extResource).map(p => path.resolve(this.rootDir, p))
|
const patterns = wrapArray(extResource).map(p => path.resolve(this.rootDir, p))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -48,28 +50,35 @@ export default class StyleLoader {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
postcss() {
|
postcss() {
|
||||||
// postcss-loader
|
// postcss-loader
|
||||||
// https://github.com/postcss/postcss-loader
|
// https://github.com/postcss/postcss-loader
|
||||||
if (this.postcssConfig) {
|
if (!this.postcssConfig) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const config = this.postcssConfig.config()
|
const config = this.postcssConfig.config()
|
||||||
if (config) {
|
|
||||||
|
if (!config) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
loader: 'postcss-loader',
|
loader: 'postcss-loader',
|
||||||
options: Object.assign({ sourceMap: this.sourceMap }, config)
|
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) {
|
||||||
|
Loading…
Reference in New Issue
Block a user