perf: early return chained functions with falsy values (#25647)

This commit is contained in:
Michael Brevard 2024-02-26 18:08:45 +02:00 committed by GitHub
parent be85a72f99
commit ff1bb56e3f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 52 additions and 44 deletions

View File

@ -89,9 +89,9 @@ export function isNuxt3 (nuxt: Nuxt = useNuxt()) {
* Get nuxt version * Get nuxt version
*/ */
export function getNuxtVersion (nuxt: Nuxt | any = useNuxt() /* TODO: LegacyNuxt */) { export function getNuxtVersion (nuxt: Nuxt | any = useNuxt() /* TODO: LegacyNuxt */) {
const version = (nuxt?._version || nuxt?.version || nuxt?.constructor?.version || '').replace(/^v/g, '') const rawVersion = nuxt?._version || nuxt?.version || nuxt?.constructor?.version
if (!version) { if (!rawVersion) {
throw new Error('Cannot determine nuxt version! Is current instance passed?') throw new Error('Cannot determine nuxt version! Is current instance passed?')
} }
return version return rawVersion.replace(/^v/g, '')
} }

View File

@ -33,7 +33,7 @@ export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
throw new Error(`Cannot find any nuxt version from ${opts.cwd}`) throw new Error(`Cannot find any nuxt version from ${opts.cwd}`)
} }
const pkg = await readPackageJSON(nearestNuxtPkg) const pkg = await readPackageJSON(nearestNuxtPkg)
const majorVersion = parseInt((pkg.version || '').split('.')[0]) const majorVersion = pkg.version ? parseInt(pkg.version.split('.')[0]) : ''
const rootDir = pathToFileURL(opts.cwd || process.cwd()).href const rootDir = pathToFileURL(opts.cwd || process.cwd()).href

View File

@ -13,7 +13,8 @@ const props = defineProps({
const _error = props.error const _error = props.error
// TODO: extract to a separate utility // TODO: extract to a separate utility
const stacktrace = (_error.stack || '') const stacktrace = _error.stack
? _error.stack
.split('\n') .split('\n')
.splice(1) .splice(1)
.map((line) => { .map((line) => {
@ -28,6 +29,7 @@ const stacktrace = (_error.stack || '')
line.includes('new Promise') line.includes('new Promise')
} }
}).map(i => `<span class="stack${i.internal ? ' internal' : ''}">${i.text}</span>`).join('\n') }).map(i => `<span class="stack${i.internal ? ' internal' : ''}">${i.text}</span>`).join('\n')
: ''
// Error page props // Error page props
const statusCode = Number(_error.statusCode || 500) const statusCode = Number(_error.statusCode || 500)

View File

@ -233,7 +233,7 @@ export function checkForCircularDependencies (_plugins: Array<NuxtPlugin & Omit<
return [] return []
} }
visited.push(name) visited.push(name)
return (deps[name] || []).flatMap(dep => checkDeps(dep, [...visited])) return deps[name]?.length ? deps[name].flatMap(dep => checkDeps(dep, [...visited])) : []
} }
for (const name in deps) { for (const name in deps) {
checkDeps(name) checkDeps(name)

View File

@ -287,8 +287,9 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
const routeRulesMatcher = toRouteMatcher( const routeRulesMatcher = toRouteMatcher(
createRadixRouter({ routes: routeRules }) createRadixRouter({ routes: routeRules })
) )
if (nitro._prerenderedRoutes?.length) {
const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? '/_payload.json' : '/_payload.js' const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? '/_payload.json' : '/_payload.js'
for (const route of nitro._prerenderedRoutes || []) { for (const route of nitro._prerenderedRoutes) {
if (!route.error && route.route.endsWith(payloadSuffix)) { if (!route.error && route.route.endsWith(payloadSuffix)) {
const url = route.route.slice(0, -payloadSuffix.length) || '/' const url = route.route.slice(0, -payloadSuffix.length) || '/'
const rules = defu({}, ...routeRulesMatcher.matchAll(url).reverse()) as Record<string, any> const rules = defu({}, ...routeRulesMatcher.matchAll(url).reverse()) as Record<string, any>
@ -297,6 +298,7 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
} }
} }
} }
}
const manifest = { const manifest = {
id: buildId, id: buildId,

View File

@ -21,11 +21,10 @@ export const DevOnlyPlugin = createUnplugin((options: DevOnlyPluginOptions) => {
if (!DEVONLY_COMP_SINGLE_RE.test(code)) { return } if (!DEVONLY_COMP_SINGLE_RE.test(code)) { return }
const s = new MagicString(code) const s = new MagicString(code)
for (const match of code.matchAll(DEVONLY_COMP_RE) || []) { for (const match of code.matchAll(DEVONLY_COMP_RE)) {
const ast: Node = parse(match[0]).children[0] const ast: Node = parse(match[0]).children[0]
const fallback: Node | undefined = ast.children?.find((n: Node) => n.name === 'template' && Object.values(n.attributes).includes('#fallback')) const fallback: Node | undefined = ast.children?.find((n: Node) => n.name === 'template' && Object.values(n.attributes).includes('#fallback'))
const replacement = fallback ? match[0].slice(fallback.loc[0].end, fallback.loc[fallback.loc.length - 1].start) : '' const replacement = fallback ? match[0].slice(fallback.loc[0].end, fallback.loc[fallback.loc.length - 1].start) : ''
s.overwrite(match.index!, match.index! + match[0].length, replacement) s.overwrite(match.index!, match.index! + match[0].length, replacement)
} }

View File

@ -31,7 +31,7 @@ export const TreeShakeComposablesPlugin = createUnplugin((options: TreeShakeComp
const s = new MagicString(code) const s = new MagicString(code)
const strippedCode = stripLiteral(code) const strippedCode = stripLiteral(code)
for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL) || []) { for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL)) {
s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} false && /*@__PURE__*/ ${match[2]}`) s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} false && /*@__PURE__*/ ${match[2]}`)
} }

View File

@ -28,7 +28,7 @@ export function resolveComponentNameSegments (fileName: string, prefixParts: str
let index = prefixParts.length - 1 let index = prefixParts.length - 1
const matchedSuffix: string[] = [] const matchedSuffix: string[] = []
while (index >= 0) { while (index >= 0) {
matchedSuffix.unshift(...splitByCase(prefixParts[index] || '').map(p => p.toLowerCase())) matchedSuffix.unshift(...splitByCase(prefixParts[index]).map(p => p.toLowerCase()))
const matchedSuffixContent = matchedSuffix.join('/') const matchedSuffixContent = matchedSuffix.join('/')
if ((fileNamePartsContent === matchedSuffixContent || fileNamePartsContent.startsWith(matchedSuffixContent + '/')) || if ((fileNamePartsContent === matchedSuffixContent || fileNamePartsContent.startsWith(matchedSuffixContent + '/')) ||
// e.g Item/Item/Item.vue -> Item // e.g Item/Item/Item.vue -> Item

View File

@ -86,10 +86,10 @@ export const NoScript = defineComponent({
}, },
setup: setupForUseMeta((props, { slots }) => { setup: setupForUseMeta((props, { slots }) => {
const noscript = { ...props } const noscript = { ...props }
const textContent = (slots.default?.() || []) const slotVnodes = slots.default?.()
.filter(({ children }) => children) const textContent = slotVnodes
.map(({ children }) => children) ? slotVnodes.filter(({ children }) => children).map(({ children }) => children).join('')
.join('') : ''
if (textContent) { if (textContent) {
noscript.children = textContent noscript.children = textContent
} }

View File

@ -271,13 +271,15 @@ export default defineNuxtModule({
processPages(pages) processPages(pages)
}) })
nuxt.hook('nitro:build:before', (nitro) => { nuxt.hook('nitro:build:before', (nitro) => {
for (const route of nitro.options.prerender.routes || []) { if (nitro.options.prerender.routes.length) {
for (const route of nitro.options.prerender.routes) {
// Skip default route value as we only generate it if it is already // Skip default route value as we only generate it if it is already
// in the detected routes from `~/pages`. // in the detected routes from `~/pages`.
if (route === '/') { continue } if (route === '/') { continue }
prerenderRoutes.add(route) prerenderRoutes.add(route)
} }
nitro.options.prerender.routes = Array.from(prerenderRoutes) nitro.options.prerender.routes = Array.from(prerenderRoutes)
}
}) })
}) })
@ -389,13 +391,13 @@ export default defineNuxtModule({
const getSources = (pages: NuxtPage[]): string[] => pages const getSources = (pages: NuxtPage[]): string[] => pages
.filter(p => Boolean(p.file)) .filter(p => Boolean(p.file))
.flatMap(p => .flatMap(p =>
[relative(nuxt.options.srcDir, p.file as string), ...getSources(p.children || [])] [relative(nuxt.options.srcDir, p.file as string), ...(p.children?.length ? getSources(p.children) : [])]
) )
// Do not prefetch page chunks // Do not prefetch page chunks
nuxt.hook('build:manifest', (manifest) => { nuxt.hook('build:manifest', (manifest) => {
if (nuxt.options.dev) { return } if (nuxt.options.dev) { return }
const sourceFiles = getSources(nuxt.apps.default.pages || []) const sourceFiles = nuxt.apps.default?.pages?.length ? getSources(nuxt.apps.default.pages) : []
for (const key in manifest) { for (const key in manifest) {
if (manifest[key].isEntry) { if (manifest[key].isEntry) {

View File

@ -144,6 +144,8 @@ export function ssrStylesPlugin (options: SSRStylePluginOptions): Plugin {
if (id === options.entry && (options.shouldInline === true || (typeof options.shouldInline === 'function' && options.shouldInline(id)))) { if (id === options.entry && (options.shouldInline === true || (typeof options.shouldInline === 'function' && options.shouldInline(id)))) {
const s = new MagicString(code) const s = new MagicString(code)
options.clientCSSMap[id] ||= new Set() options.clientCSSMap[id] ||= new Set()
if (!options.globalCSS.length) { return }
for (const file of options.globalCSS) { for (const file of options.globalCSS) {
const resolved = await this.resolve(file) ?? await this.resolve(file, id) const resolved = await this.resolve(file) ?? await this.resolve(file, id)
const res = await this.resolve(file + '?inline&used') ?? await this.resolve(file + '?inline&used', id) const res = await this.resolve(file + '?inline&used') ?? await this.resolve(file + '?inline&used', id)

View File

@ -63,7 +63,7 @@ export async function warmupViteServer (
try { try {
const mod = await server.moduleGraph.getModuleByUrl(url, isServer) const mod = await server.moduleGraph.getModuleByUrl(url, isServer)
const deps = mod?.ssrTransformResult?.deps /* server */ || Array.from(mod?.importedModules /* client */ || []).map(m => m.url) const deps = mod?.ssrTransformResult?.deps /* server */ || mod?.importedModules.size ? Array.from(mod?.importedModules /* client */).map(m => m.url) : []
await Promise.all(deps.map(m => warmup(m))) await Promise.all(deps.map(m => warmup(m)))
} catch (e) { } catch (e) {
logger.debug('[warmup] tracking dependencies for %s failed with: %s', url, e) logger.debug('[warmup] tracking dependencies for %s failed with: %s', url, e)

View File

@ -1986,6 +1986,7 @@ describe('component islands', () => {
link.href = link.href.replace(fixtureDir, '/<rootDir>').replaceAll('//', '/') link.href = link.href.replace(fixtureDir, '/<rootDir>').replaceAll('//', '/')
link.key = link.key.replace(/-[a-zA-Z0-9]+$/, '') link.key = link.key.replace(/-[a-zA-Z0-9]+$/, '')
} }
result.head.link.sort((a, b) => b.href.localeCompare(a.href))
} }
// TODO: fix rendering of styles in webpack // TODO: fix rendering of styles in webpack