diff --git a/packages/nuxt3/src/auto-imports/module.ts b/packages/nuxt3/src/auto-imports/module.ts index 8d73d8d4e0..cef97a488c 100644 --- a/packages/nuxt3/src/auto-imports/module.ts +++ b/packages/nuxt3/src/auto-imports/module.ts @@ -31,17 +31,6 @@ export default defineNuxtModule({ // Create a context to share state between module internals const ctx = createAutoImportContext(options) - // Resolve autoimports from sources - for (const source of options.sources) { - for (const importName of source.names) { - if (typeof importName === 'string') { - ctx.autoImports.push({ name: importName, as: importName, from: source.from }) - } else { - ctx.autoImports.push({ name: importName.name, as: importName.as || importName.name, from: source.from }) - } - } - } - // composables/ dirs let composablesDirs = [ join(nuxt.options.srcDir, 'composables'), @@ -76,7 +65,13 @@ export default defineNuxtModule({ addWebpackPlugin(TransformPlugin.webpack(ctx)) } - const updateAutoImports = async () => { + const regenerateAutoImports = async () => { + // Resolve autoimports from sources + ctx.autoImports = options.sources.flatMap(source => source.names.map( + importName => typeof importName === 'string' + ? { name: importName, as: importName, from: source.from } + : { name: importName.name, as: importName.as || importName.name, from: source.from } + )) // Scan composables/ for (const composablesDir of composablesDirs) { await scanForComposables(composablesDir, ctx.autoImports) @@ -85,10 +80,12 @@ export default defineNuxtModule({ await nuxt.callHook('autoImports:extend', ctx.autoImports) // Update context updateAutoImportContext(ctx) - // Generate types - generateDts(ctx) } - await updateAutoImports() + + await regenerateAutoImports() + + // Generate types + addDeclarationTemplates(ctx) // Add generated types to `nuxt.d.ts` nuxt.hook('prepare:types', ({ references }) => { @@ -100,13 +97,14 @@ export default defineNuxtModule({ nuxt.hook('builder:watch', async (_, path) => { const _resolved = resolve(nuxt.options.srcDir, path) if (composablesDirs.find(dir => _resolved.startsWith(dir))) { - await updateAutoImports() + await regenerateAutoImports() + await nuxt.callHook('builder:generateApp') } }) } }) -function generateDts (ctx: AutoImportContext) { +function addDeclarationTemplates (ctx: AutoImportContext) { const nuxt = useNuxt() const resolved = {} @@ -124,13 +122,11 @@ function generateDts (ctx: AutoImportContext) { addTemplate({ filename: 'types/imports.d.ts', - write: true, getContents: () => toExports(ctx.autoImports) }) addTemplate({ filename: 'types/auto-imports.d.ts', - write: true, getContents: () => `// Generated by auto imports declare global { ${ctx.autoImports.map(i => ` const ${i.as}: typeof ${genDynamicImport(r(i.from), { wrapper: false })}['${i.name}']`).join('\n')}