Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nuxt): auto imports regeneration timing #26249

Merged
merged 5 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 12 additions & 2 deletions packages/nuxt/src/core/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,20 @@
.filter(template => !options.filter || options.filter(template))

const writes: Array<() => void> = []
await Promise.allSettled(filteredTemplates
const result = await Promise.allSettled(filteredTemplates
.map(async (template) => {
const fullPath = template.dst || resolve(nuxt.options.buildDir, template.filename!)
const oldContents = nuxt.vfs[fullPath]
const mark = performance.mark(fullPath)
const contents = await compileTemplate(template, templateContext).catch((e) => {
logger.error(`Could not compile template \`${template.filename}\`.`)
throw e
})

if (oldContents === contents) {
return false
}

nuxt.vfs[fullPath] = contents

const aliasPath = '#build/' + template.filename!.replace(/\.\w+$/, '')
Expand All @@ -72,13 +77,18 @@
writeFileSync(fullPath, contents, 'utf8')
})
}

return true
}))

// Write template files in single synchronous step to avoid (possible) additional
// runtime overhead of cascading HMRs from vite/webpack
for (const write of writes) { write() }

await nuxt.callHook('app:templatesGenerated', app, filteredTemplates, options)
const anyTemplateUpdated = result.some(r => r.status === 'fulfilled' && r.value)
if (anyTemplateUpdated) {
await nuxt.callHook('app:templatesGenerated', app, filteredTemplates, options)
}
}

/** @internal */
Expand Down Expand Up @@ -225,7 +235,7 @@
for (const plugin of _plugins) {
// Make sure dependency plugins are registered
if (plugin.dependsOn && plugin.dependsOn.some(name => !pluginNames.includes(name))) {
console.error(`Plugin \`${plugin.name}\` depends on \`${plugin.dependsOn.filter(name => !pluginNames.includes(name)).join(', ')}\` but they are not registered.`)

Check warning on line 238 in packages/nuxt/src/core/app.ts

View workflow job for this annotation

GitHub Actions / code

Unexpected console statement
}
// Make graph to detect circular dependencies
if (plugin.name) {
Expand All @@ -234,7 +244,7 @@
}
const checkDeps = (name: string, visited: string[] = []): string[] => {
if (visited.includes(name)) {
console.error(`Circular dependency detected in plugins: ${visited.join(' -> ')} -> ${name}`)

Check warning on line 247 in packages/nuxt/src/core/app.ts

View workflow job for this annotation

GitHub Actions / code

Unexpected console statement
return []
}
visited.push(name)
Expand Down
32 changes: 21 additions & 11 deletions packages/nuxt/src/imports/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, isIgnor
import { isAbsolute, join, normalize, relative, resolve } from 'pathe'
import type { Import, Unimport } from 'unimport'
import { createUnimport, scanDirExports, toExports } from 'unimport'
import type { ImportPresetWithDeprecation, ImportsOptions } from 'nuxt/schema'
import type { ImportPresetWithDeprecation, ImportsOptions, ResolvedNuxtTemplate } from 'nuxt/schema'

import { lookupNodeModuleSubpath, parseNodeModulePath } from 'mlly'
import { isDirectory } from '../utils'
Expand Down Expand Up @@ -89,6 +89,14 @@ export default defineNuxtModule<Partial<ImportsOptions>>({

const priorities = nuxt.options._layers.map((layer, i) => [layer.config.srcDir, -i] as const).sort(([a], [b]) => b.length - a.length)

function isImportsTemplate (template: ResolvedNuxtTemplate) {
return [
'/types/imports.d.ts',
'/imports.d.ts',
'/imports.mjs'
].some(i => template.filename.endsWith(i))
}

const regenerateImports = async () => {
await ctx.modifyDynamicImports(async (imports) => {
// Clear old imports
Expand All @@ -105,6 +113,10 @@ export default defineNuxtModule<Partial<ImportsOptions>>({
await nuxt.callHook('imports:extend', imports)
return imports
})

await updateTemplates({
filter: isImportsTemplate
})
}

await regenerateImports()
Expand All @@ -119,22 +131,20 @@ export default defineNuxtModule<Partial<ImportsOptions>>({
})

// Watch composables/ directory
const templates = [
'types/imports.d.ts',
'imports.d.ts',
'imports.mjs'
]
nuxt.hook('builder:watch', async (_, relativePath) => {
const path = resolve(nuxt.options.srcDir, relativePath)
if (composablesDirs.some(dir => dir === path || path.startsWith(dir + '/'))) {
await updateTemplates({
filter: template => templates.includes(template.filename)
})
await regenerateImports()
}
})

nuxt.hook('app:templatesGenerated', async () => {
await regenerateImports()
Copy link
Member Author

@antfu antfu Mar 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously we did regeneration (rescan) after all templates to avoid race conditions in #21934. But since unimport also use templates to generate those dts etc, so it means we missed the chance to update them - until this get triggered again - we are always one "tick" behind.

This PR makes sure regenerateImports always update (only) the unimport templates. Thus we also need some mechanism to dedupe and avoid circular update

// Watch for template generation
nuxt.hook('app:templatesGenerated', async (_app, templates) => {
// Filter out templates of imports to avoid circular regeneration
const nonDtsTemplates = templates.filter(t => !isImportsTemplate(t))
antfu marked this conversation as resolved.
Show resolved Hide resolved
if (nonDtsTemplates.length) {
await regenerateImports()
}
})
}
})
Expand Down