提交 58b2d9e2 编写于 作者: A Afzal Sayed 提交者: Joe Haddad

Use optional chaining syntax (#9975)

* Use optional chaining syntax

* Changes as per review

* Bug fix
上级 7a6f0561
......@@ -87,9 +87,8 @@ async function run() {
appPath: resolvedProjectPath,
useNpm: !!program.useNpm,
example:
typeof program.example === 'string' && program.example.trim()
? program.example.trim()
: undefined,
(typeof program.example === 'string' && program.example.trim()) ||
undefined,
})
}
......@@ -98,7 +97,7 @@ const update = checkForUpdate(packageJson).catch(() => null)
async function notifyUpdate() {
try {
const res = await update
if (res && res.latest) {
if (res?.latest) {
const isYarn = shouldUseYarn()
console.log()
......
......@@ -81,13 +81,7 @@ export default function nextPageConfig({
}
if (config.amp === true) {
if (
!(
state.file &&
state.file.opts &&
state.file.opts.caller.isDev
)
) {
if (!state.file?.opts?.caller.isDev) {
// don't replace bundle in development so HMR can track
// dependencies and trigger reload when they are changed
replaceBundle(path, t)
......
......@@ -109,7 +109,7 @@ export default function nextTransformSsg({
state: PluginState
) {
const ident = getIdentifier(path)
if (ident && ident.node && isIdentifierReferenced(ident)) {
if (ident?.node && isIdentifierReferenced(ident)) {
state.refs.add(ident)
}
}
......@@ -153,8 +153,7 @@ export default function nextTransformSsg({
) {
const ident = getIdentifier(path)
if (
ident &&
ident.node &&
ident?.node &&
refs.has(ident) &&
!isIdentifierReferenced(ident)
) {
......
......@@ -54,7 +54,7 @@ type BabelPreset = {
// Taken from https://github.com/babel/babel/commit/d60c5e1736543a6eac4b549553e107a9ba967051#diff-b4beead8ad9195361b4537601cc22532R158
function supportsStaticESM(caller: any) {
return !!(caller && caller.supportsStaticESM)
return !!caller?.supportsStaticESM
}
module.exports = (
......@@ -66,8 +66,7 @@ module.exports = (
const isModern = api.caller((caller: any) => !!caller && caller.isModern)
const isLaxModern =
isModern ||
(options['preset-env'] &&
options['preset-env'].targets &&
(options['preset-env']?.targets &&
options['preset-env'].targets.esmodules === true)
const presetEnvConfig = {
......
......@@ -292,8 +292,8 @@ export function watchCompilers(
stats.toJson({ all: false, warnings: true, errors: true })
)
const hasErrors = errors && errors.length
const hasWarnings = warnings && warnings.length
const hasErrors = !!errors?.length
const hasWarnings = !!warnings?.length
onEvent({
loading: false,
......
......@@ -103,9 +103,9 @@ export async function printTreeView(
`${symbol} ${
item === '/_app'
? ' '
: pageInfo && pageInfo.static
: pageInfo?.static
? ''
: pageInfo && pageInfo.isSsg
: pageInfo?.isSsg
? ''
: 'λ'
} ${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 previewPages = totalRoutes === 4 ? 4 : 3
const contSymbol = i === arr.length - 1 ? ' ' : ''
......
......@@ -203,8 +203,8 @@ export default async function getBaseWebpackConfig(
typeScriptPath && (await fileExists(tsConfigPath))
)
const ignoreTypeScriptErrors = dev
? config.typescript && config.typescript.ignoreDevErrors
: config.typescript && config.typescript.ignoreBuildErrors
? config.typescript?.ignoreDevErrors
: config.typescript?.ignoreBuildErrors
const resolveConfig = {
// Disable .mjs for node_modules bundling
......
......@@ -10,11 +10,7 @@ export class DropClientPage implements Plugin {
Object.keys(compilation.assets).forEach(assetKey => {
const asset = compilation.assets[assetKey]
if (
asset &&
asset._value &&
asset._value.includes('__NEXT_DROP_CLIENT_FILE__')
) {
if (asset?._value?.includes?.('__NEXT_DROP_CLIENT_FILE__')) {
const cleanAssetKey = assetKey.replace(/\\/g, '/')
const page = '/' + cleanAssetKey.split('pages/')[1]
const pageNoExt = page.split(extname(page))[0]
......
......@@ -109,7 +109,7 @@ export default class NextEsmPlugin implements Plugin {
ruleLoader = ruleLoader.loader
}
if (
(ruleUse && ruleUse.loader && predicate(ruleUse.loader)) ||
(ruleUse?.loader && predicate(ruleUse.loader)) ||
(ruleLoader && predicate(ruleLoader as string))
) {
results.push(ruleUse || rule)
......@@ -228,7 +228,7 @@ export default class NextEsmPlugin implements Plugin {
compilation.chunks.forEach((chunk: compilation.Chunk) => {
const childChunk = childChunkFileMap[chunk.name]
if (childChunk && childChunk.files) {
if (childChunk?.files) {
delete childChunkFileMap[chunk.name]
chunk.files.push(
...childChunk.files.filter((v: any) => !chunk.files.includes(v))
......
......@@ -166,7 +166,7 @@ export default async function(
// default. In most cases, this would never work. There is no server that
// could run `getStaticProps`. If users make their page work lazily, they
// can manually add it to the `exportPathMap`.
if (prerenderManifest && prerenderManifest.dynamicRoutes[page]) {
if (prerenderManifest?.dynamicRoutes[page]) {
continue
}
......@@ -230,11 +230,9 @@ export default async function(
dev: false,
staticMarkup: false,
hotReloader: null,
canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || '',
canonicalBase: nextConfig.amp?.canonicalBase || '',
isModern: nextConfig.experimental.modern,
ampValidator:
(nextConfig.experimental.amp && nextConfig.experimental.amp.validator) ||
undefined,
ampValidator: nextConfig.experimental.amp?.validator || undefined,
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......@@ -333,7 +331,7 @@ export default async function(
ampValidations[page] = result
hadValidationError =
hadValidationError ||
(Array.isArray(result && result.errors) && result.errors.length > 0)
(Array.isArray(result?.errors) && result.errors.length > 0)
}
renderError = renderError || !!result.error
......
......@@ -218,7 +218,7 @@ export async function verifyTypeScriptSetup(
)
}
if (result.errors && result.errors.length) {
if (result.errors?.length) {
throw new Error(
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)
return
}
......
......@@ -245,7 +245,7 @@ export async function loadGetInitialProps<
P = {}
>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {
if (process.env.NODE_ENV !== 'production') {
if (App.prototype && App.prototype.getInitialProps) {
if (App.prototype?.getInitialProps) {
const message = `"${getDisplayName(
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.`
......
......@@ -172,7 +172,7 @@ export default function loadConfig(
})
// If config file was found
if (path && path.length) {
if (path?.length) {
const userConfigModule = require(path)
const userConfig = normalizeConfig(
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)
userConfig.amp = userConfig.amp || {}
userConfig.amp.canonicalBase =
......@@ -210,8 +210,7 @@ export default function loadConfig(
}
if (
userConfig.experimental &&
userConfig.experimental.reactMode &&
userConfig.experimental?.reactMode &&
!reactModes.includes(userConfig.experimental.reactMode)
) {
throw new Error(
......@@ -233,7 +232,7 @@ export default function loadConfig(
],
{ cwd: dir }
)
if (nonJsPath && nonJsPath.length) {
if (nonJsPath?.length) {
throw new Error(
`Configuring Next.js via '${basename(
nonJsPath
......
......@@ -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(
req as NextApiRequest,
res as NextApiResponse,
......
......@@ -198,7 +198,7 @@ export default class HotReloader {
// Make sure to 404 for AMP first pages
try {
const mod = require(bundlePath)
if (mod && mod.config && mod.config.amp === true) {
if (mod?.config?.amp === true) {
res.statusCode = 404
res.end()
return { finished: true }
......
......@@ -144,7 +144,7 @@ export default class DevServer extends Server {
// Watchpack doesn't emit an event for an empty directory
fs.readdir(pagesDir!, (_, files) => {
if (files && files.length) {
if (files?.length) {
return
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册