Use optional chaining syntax (#9975)

* Use optional chaining syntax

* Changes as per review

* Bug fix
This commit is contained in:
Afzal Sayed 2020-01-08 22:00:53 +05:30 committed by Joe Haddad
parent 7a6f056192
commit 58b2d9e208
16 changed files with 32 additions and 48 deletions

View file

@ -87,9 +87,8 @@ async function run() {
appPath: resolvedProjectPath, appPath: resolvedProjectPath,
useNpm: !!program.useNpm, useNpm: !!program.useNpm,
example: example:
typeof program.example === 'string' && program.example.trim() (typeof program.example === 'string' && program.example.trim()) ||
? program.example.trim() undefined,
: undefined,
}) })
} }
@ -98,7 +97,7 @@ const update = checkForUpdate(packageJson).catch(() => null)
async function notifyUpdate() { async function notifyUpdate() {
try { try {
const res = await update const res = await update
if (res && res.latest) { if (res?.latest) {
const isYarn = shouldUseYarn() const isYarn = shouldUseYarn()
console.log() console.log()

View file

@ -81,13 +81,7 @@ export default function nextPageConfig({
} }
if (config.amp === true) { if (config.amp === true) {
if ( if (!state.file?.opts?.caller.isDev) {
!(
state.file &&
state.file.opts &&
state.file.opts.caller.isDev
)
) {
// don't replace bundle in development so HMR can track // don't replace bundle in development so HMR can track
// dependencies and trigger reload when they are changed // dependencies and trigger reload when they are changed
replaceBundle(path, t) replaceBundle(path, t)

View file

@ -109,7 +109,7 @@ export default function nextTransformSsg({
state: PluginState state: PluginState
) { ) {
const ident = getIdentifier(path) const ident = getIdentifier(path)
if (ident && ident.node && isIdentifierReferenced(ident)) { if (ident?.node && isIdentifierReferenced(ident)) {
state.refs.add(ident) state.refs.add(ident)
} }
} }
@ -153,8 +153,7 @@ export default function nextTransformSsg({
) { ) {
const ident = getIdentifier(path) const ident = getIdentifier(path)
if ( if (
ident && ident?.node &&
ident.node &&
refs.has(ident) && refs.has(ident) &&
!isIdentifierReferenced(ident) !isIdentifierReferenced(ident)
) { ) {

View file

@ -54,7 +54,7 @@ type BabelPreset = {
// Taken from https://github.com/babel/babel/commit/d60c5e1736543a6eac4b549553e107a9ba967051#diff-b4beead8ad9195361b4537601cc22532R158 // Taken from https://github.com/babel/babel/commit/d60c5e1736543a6eac4b549553e107a9ba967051#diff-b4beead8ad9195361b4537601cc22532R158
function supportsStaticESM(caller: any) { function supportsStaticESM(caller: any) {
return !!(caller && caller.supportsStaticESM) return !!caller?.supportsStaticESM
} }
module.exports = ( module.exports = (
@ -66,8 +66,7 @@ module.exports = (
const isModern = api.caller((caller: any) => !!caller && caller.isModern) const isModern = api.caller((caller: any) => !!caller && caller.isModern)
const isLaxModern = const isLaxModern =
isModern || isModern ||
(options['preset-env'] && (options['preset-env']?.targets &&
options['preset-env'].targets &&
options['preset-env'].targets.esmodules === true) options['preset-env'].targets.esmodules === true)
const presetEnvConfig = { const presetEnvConfig = {

View file

@ -292,8 +292,8 @@ export function watchCompilers(
stats.toJson({ all: false, warnings: true, errors: true }) stats.toJson({ all: false, warnings: true, errors: true })
) )
const hasErrors = errors && errors.length const hasErrors = !!errors?.length
const hasWarnings = warnings && warnings.length const hasWarnings = !!warnings?.length
onEvent({ onEvent({
loading: false, loading: false,

View file

@ -103,9 +103,9 @@ export async function printTreeView(
`${symbol} ${ `${symbol} ${
item === '/_app' item === '/_app'
? ' ' ? ' '
: pageInfo && pageInfo.static : pageInfo?.static
? '○' ? '○'
: pageInfo && pageInfo.isSsg : pageInfo?.isSsg
? '●' ? '●'
: 'λ' : 'λ'
} ${item}`, } ${item}`,
@ -118,7 +118,7 @@ export async function printTreeView(
: '', : '',
]) ])
if (pageInfo && pageInfo.ssgPageRoutes && pageInfo.ssgPageRoutes.length) { if (pageInfo?.ssgPageRoutes?.length) {
const totalRoutes = pageInfo.ssgPageRoutes.length const totalRoutes = pageInfo.ssgPageRoutes.length
const previewPages = totalRoutes === 4 ? 4 : 3 const previewPages = totalRoutes === 4 ? 4 : 3
const contSymbol = i === arr.length - 1 ? ' ' : '├' const contSymbol = i === arr.length - 1 ? ' ' : '├'

View file

@ -203,8 +203,8 @@ export default async function getBaseWebpackConfig(
typeScriptPath && (await fileExists(tsConfigPath)) typeScriptPath && (await fileExists(tsConfigPath))
) )
const ignoreTypeScriptErrors = dev const ignoreTypeScriptErrors = dev
? config.typescript && config.typescript.ignoreDevErrors ? config.typescript?.ignoreDevErrors
: config.typescript && config.typescript.ignoreBuildErrors : config.typescript?.ignoreBuildErrors
const resolveConfig = { const resolveConfig = {
// Disable .mjs for node_modules bundling // Disable .mjs for node_modules bundling

View file

@ -10,11 +10,7 @@ export class DropClientPage implements Plugin {
Object.keys(compilation.assets).forEach(assetKey => { Object.keys(compilation.assets).forEach(assetKey => {
const asset = compilation.assets[assetKey] const asset = compilation.assets[assetKey]
if ( if (asset?._value?.includes?.('__NEXT_DROP_CLIENT_FILE__')) {
asset &&
asset._value &&
asset._value.includes('__NEXT_DROP_CLIENT_FILE__')
) {
const cleanAssetKey = assetKey.replace(/\\/g, '/') const cleanAssetKey = assetKey.replace(/\\/g, '/')
const page = '/' + cleanAssetKey.split('pages/')[1] const page = '/' + cleanAssetKey.split('pages/')[1]
const pageNoExt = page.split(extname(page))[0] const pageNoExt = page.split(extname(page))[0]

View file

@ -109,7 +109,7 @@ export default class NextEsmPlugin implements Plugin {
ruleLoader = ruleLoader.loader ruleLoader = ruleLoader.loader
} }
if ( if (
(ruleUse && ruleUse.loader && predicate(ruleUse.loader)) || (ruleUse?.loader && predicate(ruleUse.loader)) ||
(ruleLoader && predicate(ruleLoader as string)) (ruleLoader && predicate(ruleLoader as string))
) { ) {
results.push(ruleUse || rule) results.push(ruleUse || rule)
@ -228,7 +228,7 @@ export default class NextEsmPlugin implements Plugin {
compilation.chunks.forEach((chunk: compilation.Chunk) => { compilation.chunks.forEach((chunk: compilation.Chunk) => {
const childChunk = childChunkFileMap[chunk.name] const childChunk = childChunkFileMap[chunk.name]
if (childChunk && childChunk.files) { if (childChunk?.files) {
delete childChunkFileMap[chunk.name] delete childChunkFileMap[chunk.name]
chunk.files.push( chunk.files.push(
...childChunk.files.filter((v: any) => !chunk.files.includes(v)) ...childChunk.files.filter((v: any) => !chunk.files.includes(v))

View file

@ -166,7 +166,7 @@ export default async function(
// default. In most cases, this would never work. There is no server that // default. In most cases, this would never work. There is no server that
// could run `getStaticProps`. If users make their page work lazily, they // could run `getStaticProps`. If users make their page work lazily, they
// can manually add it to the `exportPathMap`. // can manually add it to the `exportPathMap`.
if (prerenderManifest && prerenderManifest.dynamicRoutes[page]) { if (prerenderManifest?.dynamicRoutes[page]) {
continue continue
} }
@ -230,11 +230,9 @@ export default async function(
dev: false, dev: false,
staticMarkup: false, staticMarkup: false,
hotReloader: null, hotReloader: null,
canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || '', canonicalBase: nextConfig.amp?.canonicalBase || '',
isModern: nextConfig.experimental.modern, isModern: nextConfig.experimental.modern,
ampValidator: ampValidator: nextConfig.experimental.amp?.validator || undefined,
(nextConfig.experimental.amp && nextConfig.experimental.amp.validator) ||
undefined,
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
@ -333,7 +331,7 @@ export default async function(
ampValidations[page] = result ampValidations[page] = result
hadValidationError = hadValidationError =
hadValidationError || hadValidationError ||
(Array.isArray(result && result.errors) && result.errors.length > 0) (Array.isArray(result?.errors) && result.errors.length > 0)
} }
renderError = renderError || !!result.error renderError = renderError || !!result.error

View file

@ -218,7 +218,7 @@ export async function verifyTypeScriptSetup(
) )
} }
if (result.errors && result.errors.length) { if (result.errors?.length) {
throw new Error( throw new Error(
ts.formatDiagnostic(result.errors[0], formatDiagnosticHost) ts.formatDiagnostic(result.errors[0], formatDiagnosticHost)
) )
@ -236,7 +236,7 @@ export async function verifyTypeScriptSetup(
) )
} }
console.info(e && e.message ? `${e.message}` : '') console.info(e?.message ? `${e.message}` : '')
process.exit(1) process.exit(1)
return return
} }

View file

@ -245,7 +245,7 @@ export async function loadGetInitialProps<
P = {} P = {}
>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> { >(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (App.prototype && App.prototype.getInitialProps) { if (App.prototype?.getInitialProps) {
const message = `"${getDisplayName( const message = `"${getDisplayName(
App App
)}.getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information.` )}.getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information.`

View file

@ -172,7 +172,7 @@ export default function loadConfig(
}) })
// If config file was found // If config file was found
if (path && path.length) { if (path?.length) {
const userConfigModule = require(path) const userConfigModule = require(path)
const userConfig = normalizeConfig( const userConfig = normalizeConfig(
phase, phase,
@ -186,7 +186,7 @@ export default function loadConfig(
) )
} }
if (userConfig.amp && userConfig.amp.canonicalBase) { if (userConfig.amp?.canonicalBase) {
const { canonicalBase } = userConfig.amp || ({} as any) const { canonicalBase } = userConfig.amp || ({} as any)
userConfig.amp = userConfig.amp || {} userConfig.amp = userConfig.amp || {}
userConfig.amp.canonicalBase = userConfig.amp.canonicalBase =
@ -210,8 +210,7 @@ export default function loadConfig(
} }
if ( if (
userConfig.experimental && userConfig.experimental?.reactMode &&
userConfig.experimental.reactMode &&
!reactModes.includes(userConfig.experimental.reactMode) !reactModes.includes(userConfig.experimental.reactMode)
) { ) {
throw new Error( throw new Error(
@ -233,7 +232,7 @@ export default function loadConfig(
], ],
{ cwd: dir } { cwd: dir }
) )
if (nonJsPath && nonJsPath.length) { if (nonJsPath?.length) {
throw new Error( throw new Error(
`Configuring Next.js via '${basename( `Configuring Next.js via '${basename(
nonJsPath nonJsPath

View file

@ -532,7 +532,7 @@ export default class Server {
} }
} }
if (params && params.path && params.path[0] === 'api') { if (params?.path?.[0] === 'api') {
const handled = await this.handleApiRequest( const handled = await this.handleApiRequest(
req as NextApiRequest, req as NextApiRequest,
res as NextApiResponse, res as NextApiResponse,

View file

@ -198,7 +198,7 @@ export default class HotReloader {
// Make sure to 404 for AMP first pages // Make sure to 404 for AMP first pages
try { try {
const mod = require(bundlePath) const mod = require(bundlePath)
if (mod && mod.config && mod.config.amp === true) { if (mod?.config?.amp === true) {
res.statusCode = 404 res.statusCode = 404
res.end() res.end()
return { finished: true } return { finished: true }

View file

@ -144,7 +144,7 @@ export default class DevServer extends Server {
// Watchpack doesn't emit an event for an empty directory // Watchpack doesn't emit an event for an empty directory
fs.readdir(pagesDir!, (_, files) => { fs.readdir(pagesDir!, (_, files) => {
if (files && files.length) { if (files?.length) {
return return
} }