refactor: cleanups and code style improvements (#4788)

This commit is contained in:
Alexander Lichter 2019-01-17 21:18:29 +00:00 committed by Pooya Parsa
parent db4001dae1
commit 40fbe5ba47
21 changed files with 60 additions and 57 deletions

View File

@ -46,7 +46,7 @@ module.exports = (context, options = {}) => {
decoratorsLegacy
} = options
let targets = options.targets
let { targets } = options
if (modern === true) {
targets = { esmodules: true }
} else if (targets === undefined) {

View File

@ -96,7 +96,7 @@ export default class Builder {
const context = new BuildContext(this)
if (typeof BundleBuilder !== 'function') {
BundleBuilder = require('@nuxt/webpack').BundleBuilder
({ BundleBuilder } = require('@nuxt/webpack'))
}
return new BundleBuilder(context)
@ -384,7 +384,7 @@ export default class Builder {
} else if (this._nuxtPages) {
// Use nuxt.js createRoutes bases on pages/
const files = {}
; (await glob(`${this.options.dir.pages}/**/*.{${this.supportedExtensions.join(',')}}`, {
;(await glob(`${this.options.dir.pages}/**/*.{${this.supportedExtensions.join(',')}}`, {
cwd: this.options.srcDir,
ignore: this.options.ignore
})).forEach((f) => {
@ -637,7 +637,7 @@ export default class Builder {
.watch(customPatterns, options)
.on('change', refreshFiles)
const rewatchOnRawEvents = this.options.watchers.rewatchOnRawEvents
const { rewatchOnRawEvents } = this.options.watchers
if (rewatchOnRawEvents && Array.isArray(rewatchOnRawEvents)) {
this.watchers.custom.on('raw', (_event, _path, opts) => {
if (rewatchOnRawEvents.includes(_event)) {

View File

@ -13,7 +13,7 @@ export default {
},
async run(cmd) {
const argv = cmd.argv
const { argv } = cmd
await this.startDev(cmd, argv)
},

View File

@ -13,7 +13,7 @@ export default {
version: common.version
},
async run(cmd) {
const name = cmd._argv[0]
const [name] = cmd._argv
if (!name) {
return listCommands()
}

View File

@ -180,7 +180,8 @@ export function getNuxtConfig(_options) {
}
// Apply default hash to CSP option
const csp = options.render.csp
const { csp } = options.render
const cspDefaults = {
hashAlgorithm: 'sha256',
allowedSources: undefined,
@ -297,7 +298,7 @@ export function getNuxtConfig(_options) {
options.build.optimizeCSS = options.build.extractCSS ? {} : false
}
const loaders = options.build.loaders
const { loaders } = options.build
const vueLoader = loaders.vue
if (vueLoader.productionMode === undefined) {
vueLoader.productionMode = !options.dev

View File

@ -121,13 +121,10 @@ export default class ModuleContainer {
src = moduleOpts
} else if (Array.isArray(moduleOpts)) {
// Type 2: Babel style array
src = moduleOpts[0]
options = moduleOpts[1]
[src, options] = moduleOpts
} else if (typeof moduleOpts === 'object') {
// Type 3: Pure object
src = moduleOpts.src
options = moduleOpts.options
handler = moduleOpts.handler
({ src, options, handler } = moduleOpts)
}
// Resolve handler

View File

@ -205,7 +205,7 @@ export default class Generator {
_generate: true,
payload
})
html = res.html
;({ html } = res)
if (res.error) {
pageErrors.push({ type: 'handled', route, error: res.error })
}

View File

@ -46,7 +46,7 @@ const detectModernBrowser = ({ socket = {}, headers }) => {
const setModernMode = (req, options) => {
const { socket = {} } = req
const isModernBrowser = socket.isModernBrowser
const { isModernBrowser } = socket
if (options.modern === 'server') {
req.modernMode = isModernBrowser
}

View File

@ -105,7 +105,7 @@ const defaultPushAssets = (preloadFiles, shouldPush, publicPath, options) => {
return
}
const crossorigin = options.build.crossorigin
const { crossorigin } = options.build
const cors = `${crossorigin ? ` crossorigin=${crossorigin};` : ''}`
const ref = modern ? 'modulepreload' : 'preload'

View File

@ -64,7 +64,7 @@ export default class Server {
// Compression middleware for production
if (!this.options.dev) {
const compressor = this.options.render.compressor
const { compressor } = this.options.render
if (typeof compressor === 'object') {
// If only setting for `compression` are provided, require the module and insert
const compression = this.nuxt.resolver.requireModule('compression')

View File

@ -14,19 +14,19 @@ export const chainFn = function chainFn(base, fn) {
if (typeof fn !== 'function') {
return base
}
return function () {
return function (...args) {
if (typeof base !== 'function') {
return fn.apply(this, arguments)
return fn.apply(this, args)
}
let baseResult = base.apply(this, arguments)
let baseResult = base.apply(this, args)
// Allow function to mutate the first argument instead of returning the result
if (baseResult === undefined) {
baseResult = arguments[0]
[baseResult] = args
}
const fnResult = fn.call(
this,
baseResult,
...Array.prototype.slice.call(arguments, 1)
...Array.prototype.slice.call(args, 1)
)
// Return mutated argument if no result was returned
if (fnResult === undefined) {

View File

@ -52,12 +52,11 @@ export default class VueRenderer {
renderScripts(context) {
if (this.context.options.modern === 'client') {
const publicPath = this.context.options.build.publicPath
const { publicPath, crossorigin } = this.context.options.build
const scriptPattern = /<script[^>]*?src="([^"]*?)"[^>]*?>[^<]*?<\/script>/g
return context.renderScripts().replace(scriptPattern, (scriptTag, jsFile) => {
const legacyJsFile = jsFile.replace(publicPath, '')
const modernJsFile = this.assetsMapping[legacyJsFile]
const crossorigin = this.context.options.build.crossorigin
const cors = `${crossorigin ? ` crossorigin="${crossorigin}"` : ''}`
const moduleTag = modernJsFile
? scriptTag
@ -94,7 +93,7 @@ export default class VueRenderer {
renderResourceHints(context) {
if (this.context.options.modern === 'client') {
const publicPath = this.context.options.build.publicPath
const { publicPath, crossorigin } = this.context.options.build
const linkPattern = /<link[^>]*?href="([^"]*?)"[^>]*?as="script"[^>]*?>/g
return context.renderResourceHints().replace(linkPattern, (linkTag, jsFile) => {
const legacyJsFile = jsFile.replace(publicPath, '')
@ -102,7 +101,6 @@ export default class VueRenderer {
if (!modernJsFile) {
return ''
}
const crossorigin = this.context.options.build.crossorigin
const cors = `${crossorigin ? ` crossorigin="${crossorigin}"` : ''}`
return linkTag.replace('rel="preload"', `rel="modulepreload"${cors}`).replace(legacyJsFile, modernJsFile)
})
@ -145,7 +143,7 @@ export default class VueRenderer {
loadResources(_fs, isMFS = false) {
const distPath = path.resolve(this.context.options.buildDir, 'dist', 'server')
const updated = []
const resourceMap = this.resourceMap
const { resourceMap } = this
const readResource = (fileName, encoding) => {
try {

View File

@ -73,10 +73,9 @@ export default class SPAMetaRenderer {
meta.resourceHints = ''
const clientManifest = this.renderer.context.resources.clientManifest
const { clientManifest } = this.renderer.context.resources
const shouldPreload = this.options.render.bundleRenderer.shouldPreload
const shouldPrefetch = this.options.render.bundleRenderer.shouldPrefetch
const { shouldPreload, shouldPrefetch } = this.options.render.bundleRenderer
if (this.options.render.resourceHints && clientManifest) {
const publicPath = clientManifest.publicPath || '/_nuxt/'

View File

@ -38,7 +38,7 @@ export class WebpackBundler {
}
async build() {
const options = this.context.options
const { options } = this.context
const compilersOptions = []
@ -78,7 +78,7 @@ export class WebpackBundler {
}
// Check styleResource existence
const styleResources = this.context.options.build.styleResources
const { styleResources } = this.context.options.build
if (styleResources && Object.keys(styleResources).length) {
consola.warn(
'Using styleResources without the nuxt-style-resources-module is not suggested and can lead to severe performance issues.',
@ -123,7 +123,7 @@ export class WebpackBundler {
}
async webpackCompile(compiler) {
const name = compiler.options.name
const { name } = compiler.options
const { nuxt, options } = this.context
await nuxt.callHook('build:compile', { name, compiler })
@ -180,7 +180,7 @@ export class WebpackBundler {
webpackDev(compiler) {
consola.debug('Adding webpack middleware...')
const name = compiler.options.name
const { name } = compiler.options
const { nuxt: { server }, options } = this.context
// Create webpack dev middleware

View File

@ -19,7 +19,7 @@ export default class WebpackClientConfig extends WebpackBaseConfig {
getFileName(...args) {
if (this.options.build.analyze) {
const key = args[0]
const [key] = args
if (['app', 'chunk'].includes(key)) {
return `${this.isModern ? 'modern-' : ''}[name].js`
}

View File

@ -7,15 +7,16 @@ export default class CorsPlugin {
const ID = `vue-cors-plugin`
compiler.hooks.compilation.tap(ID, (compilation) => {
compilation.hooks.htmlWebpackPluginAlterAssetTags.tap(ID, (data) => {
if (this.crossorigin != null) {
if (!this.crossorigin) {
return
}
[...data.head, ...data.body].forEach((tag) => {
if (tag.tagName === 'script' || tag.tagName === 'link') {
if (['script', 'link'].includes(tag.tagName)) {
if (tag.attributes) {
tag.attributes.crossorigin = this.crossorigin
}
}
})
}
})
})
}

View File

@ -12,7 +12,7 @@ export default class VueSSRServerPlugin {
onEmit(compiler, 'vue-server-plugin', (compilation, cb) => {
const stats = compilation.getStats().toJson()
const entryName = Object.keys(stats.entrypoints)[0]
const [entryName] = Object.keys(stats.entrypoints)
const entryInfo = stats.entrypoints[entryName]
if (!entryInfo) {
@ -29,7 +29,7 @@ export default class VueSSRServerPlugin {
)
}
const entry = entryAssets[0]
const [entry] = entryAssets
if (!entry || typeof entry !== 'string') {
throw new Error(
`Entry "${entryName}" not found. Did you specify the correct entry option?`

View File

@ -108,7 +108,7 @@ export default class PostcssConfig {
}
loadPlugins(config) {
const plugins = config.plugins
const { plugins } = config
if (isPureObject(plugins)) {
// Map postcss plugins into instances on object mode once
config.plugins = this.sortPlugins(config)

View File

@ -107,7 +107,8 @@ export default class Package {
tryRequire(id) {
try {
return require(id)
} catch (e) {}
} catch (e) {
}
}
suffixAndVersion() {
@ -132,7 +133,7 @@ export default class Package {
}
if (typeof this.pkg.bin === 'string') {
const bin = this.pkg.bin
const { bin } = this.pkg
this.pkg.bin = {
[oldPkgName]: bin,
[this.pkg.name]: bin
@ -217,13 +218,16 @@ export default class Package {
watcher.on('event', (event) => {
switch (event.code) {
// The watcher is (re)starting
case 'START': return this.logger.debug('Watching for changes')
case 'START':
return this.logger.debug('Watching for changes')
// Building an individual bundle
case 'BUNDLE_START': return this.logger.debug('Building bundle')
case 'BUNDLE_START':
return this.logger.debug('Building bundle')
// Finished building a bundle
case 'BUNDLE_END': return
case 'BUNDLE_END':
return
// Finished building all bundles
case 'END':
@ -231,13 +235,16 @@ export default class Package {
return this.logger.success('Bundle built')
// Encountered an error while bundling
case 'ERROR': return this.logger.error(event.error)
case 'ERROR':
return this.logger.error(event.error)
// Eencountered an unrecoverable error
case 'FATAL': return this.logger.fatal(event.error)
case 'FATAL':
return this.logger.fatal(event.error)
// Unknown event
default: return this.logger.info(JSON.stringify(event))
default:
return this.logger.info(JSON.stringify(event))
}
})
} else {

View File

@ -3,7 +3,7 @@ import { buildFixture } from '../../utils/build'
describe('missing-pages-dir', () => {
buildFixture('missing-pages-dir', (builder) => {
const options = builder.nuxt.options
const { options } = builder.nuxt
expect(consola.warn).toHaveBeenCalledTimes(1)
expect(consola.warn).toHaveBeenCalledWith(`No \`${options.dir.pages}\` directory found in ${options.srcDir}. Using the default built-in page.`)
})

View File

@ -23,7 +23,7 @@ const close = async (nuxtInt) => {
describe.skip.win('cli', () => {
test('nuxt dev', async () => {
let stdout = ''
const env = process.env
const { env } = process
env.PORT = port = await getPort()
const nuxtDev = spawnNuxt('dev', { env })
@ -52,7 +52,7 @@ describe.skip.win('cli', () => {
let stdout = ''
let error
const env = process.env
const { env } = process
env.PORT = port = await getPort()
await new Promise((resolve) => {