Skip to content

Conversation

@danielroe
Copy link
Member

🔗 Linked issue

resolves #33196

📚 Description

with moduleDependencies, it was possible for modules to be added after core nuxt modules like the imports module.

this PR adapts the logic of the imports module to move the creation of the unimport context after all modules have run.

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@coderabbitai
Copy link

coderabbitai bot commented Sep 11, 2025

Warning

Rate limit exceeded

@danielroe has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 19 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 22a545b and 6a59b73.

📒 Files selected for processing (1)
  • packages/nuxt/src/imports/module.ts (6 hunks)

Walkthrough

  • Deferred Unimport context creation to a modules:done hook; ctx is declared upfront and initialised after all modules register, followed by running imports:context.
  • Moved imports:sources and imports:dirs hooks, composables directories normalisation, and imports regeneration to run inside modules:done.
  • Guarded pushing undefined directories when collecting from layers.
  • Updated TransformPlugin to accept a narrowed ctx exposing only injectImports and wired it with a lazy proxy calling ctx.injectImports.
  • Changed addDeclarationTemplates signature to accept a Pick of Unimport with getImports and generateTypeDeclarations; call site now passes a wrapper exposing only these methods.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks (4 passed, 1 warning)

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly and accurately summarises the primary change: moving the imports (Unimport) logic to run after all Nuxt modules. It is concise, specific to the main change, and suitable for a teammate scanning the history.
Linked Issues Check ✅ Passed The changes satisfy the primary coding objective of linked issue [#33196] by deferring Unimport context creation and imports/source hooks to the modules:done phase so modules added via moduleDependencies are included before types and imports are generated; the PR also schedules imports regeneration after modules finish and updates helper signatures accordingly. These edits directly address the issue's symptom (missing global/auto-imported types from dependent modules) and are scoped to the import/type generation logic in the summaries provided. Overall, the code-level changes shown appear to meet the linked issue's requirements.
Out of Scope Changes Check ✅ Passed No out-of-scope changes are apparent from the summaries: edits are confined to the imports module, its transform plugin, and a related helper signature change, all of which are directly related to deferring initialization and wiring type declaration generation. The narrowed public typings and helper signature updates are consistent with the refactor to use a smaller ctx surface and appear in-scope for this fix. There are no indications of unrelated feature additions or unrelated file changes in the provided summaries.
Description Check ✅ Passed The PR description is directly related to the changeset and cites the linked issue, explaining the problem with moduleDependencies and summarising the fix to defer Unimport context creation until after all modules run. The level of detail is sufficient for this lenient check.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/imports-order

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/nuxt/src/imports/transform.ts (1)

13-13: Type narrowing looks good; consider normalising id earlier for consistency.

The switch to Pick<Unimport, 'injectImports'> is sound and tightens the surface area. One small consistency win: normalise id in transformInclude before running include/exclude regexes (you already normalise in transform). This avoids platform-specific path mismatches.

Apply:

 export const TransformPlugin = ({ ctx, options, sourcemap }: { ctx: Pick<Unimport, 'injectImports'>, options: Partial<ImportsOptions>, sourcemap?: boolean }) => createUnplugin(() => {
   return {
     name: 'nuxt:imports-transform',
     enforce: 'post',
     transformInclude (id) {
+      id = normalize(id)
       // Included
       if (options.transform?.include?.some(pattern => pattern.test(id))) {
         return true
       }
       // Excluded
       if (options.transform?.exclude?.some(pattern => pattern.test(id))) {
         return false
       }
packages/nuxt/src/imports/module.ts (3)

74-77: Deferring imports:dirs and path normalisation is correct; also normalise the watcher path.

You normalise composablesDirs on modules:done. For symmetric comparisons in the watcher, normalise path too to avoid separator issues on Windows.

Apply:

-        const path = resolve(nuxt.options.srcDir, relativePath)
+        const path = normalize(resolve(nuxt.options.srcDir, relativePath))

91-116: Initialising ctx on modules:done — please verify no early access; optional hardening with a ctxReady gate.

Everything that uses ctx appears to execute after modules:done, but there’s an implicit ordering assumption (e.g. template getters and the transform plugin wrapper). To be belt-and-braces, gate access behind a promise so accidental early calls don’t throw if ordering changes.

Minimal hardening:

-    let ctx: Unimport
+    let ctx: Unimport
+    let resolveCtx!: (u: Unimport) => void
+    const ctxReady = new Promise<Unimport>(r => { resolveCtx = r })

     // initialise unimport only after all modules
     // have had a chance to register their hooks
     nuxt.hook('modules:done', async () => {
       await nuxt.callHook('imports:sources', presets)

       const { addons: inlineAddons, ...rest } = options
       const [addons, addonsOptions] = Array.isArray(inlineAddons) ? [inlineAddons] : [[], inlineAddons]

       // Create a context to share state between module internals
       ctx = createUnimport({
         injectAtEnd: true,
         ...rest,
         addons: {
           addons,
           vueTemplate: options.autoImport,
           vueDirectives: options.autoImport === false ? undefined : true,
           ...addonsOptions,
         },
         presets,
       })

       await nuxt.callHook('imports:context', ctx)
+      resolveCtx(ctx)
     })

And adapt the two main access sites:

-    addTemplate({
+    addTemplate({
       filename: 'imports.mjs',
-      getContents: async () => toExports(await ctx.getImports()) + '\nif (import.meta.dev) { console.warn("[nuxt] `#imports` should be transformed with real imports. There seems to be something wrong with the imports plugin.") }',
+      getContents: async () => {
+        const i = await ctxReady
+        return toExports(await i.getImports()) + '\nif (import.meta.dev) { console.warn("[nuxt] `#imports` should be transformed with real imports. There seems to be something wrong with the imports plugin.") }'
+      },
     })
-    addBuildPlugin(TransformPlugin({
-      ctx: { injectImports: (code, id, options) => ctx.injectImports(code, id, options) },
+    addBuildPlugin(TransformPlugin({
+      ctx: { injectImports: async (code, id, options) => (await ctxReady).injectImports(code, id, options) },
       options, sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client,
     }))

Optionally, mirror this pattern for addDeclarationTemplates wrappers for complete consistency.


139-140: Compute nuxtImports after imports:sources mutates presets.

presets can be extended in imports:sources. Computing nuxtImports before that may miss newly contributed internal imports, weakening the override warning.

Apply:

-    const nuxtImportSources = new Set(allNuxtPresets.flatMap(i => i.from))
-    const nuxtImports = new Set(presets.flatMap(p => nuxtImportSources.has(p.from) ? p.imports : []))
+    const nuxtImportSources = new Set(allNuxtPresets.flatMap(i => i.from))
+    let nuxtImports = new Set<string>()

Then after await nuxt.callHook('imports:sources', presets):

+      // Recompute internal-import names after sources have been extended
+      nuxtImports = new Set(presets.flatMap(p => nuxtImportSources.has(p.from) ? p.imports : []))
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f7624b and 22a545b.

📒 Files selected for processing (2)
  • packages/nuxt/src/imports/module.ts (5 hunks)
  • packages/nuxt/src/imports/transform.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • packages/nuxt/src/imports/module.ts
  • packages/nuxt/src/imports/transform.ts
🧬 Code graph analysis (2)
packages/nuxt/src/imports/module.ts (2)
packages/nuxt/src/imports/transform.ts (1)
  • TransformPlugin (13-58)
packages/schema/src/types/imports.ts (1)
  • ImportsOptions (3-36)
packages/nuxt/src/imports/transform.ts (1)
packages/nuxt/src/components/plugins/transform.ts (1)
  • TransformPlugin (22-140)
🔇 Additional comments (5)
packages/nuxt/src/imports/module.ts (5)

68-70: Guarding against falsey custom dirs — good catch.

Prevents pushing undefined/empty entries when resolving user-specified import dirs from layers.


125-128: Plugin wiring with narrowed ctx is clean.

The lazy wrapper focuses exposure to injectImports and keeps the transform isolated from the full context.


176-176: Regenerating imports on modules:done is aligned with the sequencing goal.

Ensures scanning and dynamic imports reflect all registered modules.


179-183: Narrowed ctx for declarations is appropriate.

Limiting to getImports/generateTypeDeclarations clarifies intent and reduces coupling.


202-262: Signature change for addDeclarationTemplates is clear and contained.

The inner usage matches the narrowed ctx; no issues spotted.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Sep 11, 2025

Open in StackBlitz

@nuxt/kit

npm i https://pkg.pr.new/@nuxt/kit@33214

nuxt

npm i https://pkg.pr.new/nuxt@33214

@nuxt/rspack-builder

npm i https://pkg.pr.new/@nuxt/rspack-builder@33214

@nuxt/schema

npm i https://pkg.pr.new/@nuxt/schema@33214

@nuxt/vite-builder

npm i https://pkg.pr.new/@nuxt/vite-builder@33214

@nuxt/webpack-builder

npm i https://pkg.pr.new/@nuxt/webpack-builder@33214

commit: 6a59b73

@codspeed-hq
Copy link

codspeed-hq bot commented Sep 11, 2025

CodSpeed Performance Report

Merging #33214 will not alter performance

Comparing fix/imports-order (6a59b73) with main (3f7624b)1

Summary

✅ 10 untouched

Footnotes

  1. No successful run was found on main (be49123) during the generation of this report, so 3f7624b was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

@danielroe danielroe merged commit 0dcc386 into main Sep 11, 2025
45 of 46 checks passed
@danielroe danielroe deleted the fix/imports-order branch September 11, 2025 21:37
@github-actions github-actions bot mentioned this pull request Sep 11, 2025
@github-actions github-actions bot mentioned this pull request Sep 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Using moduleDependencies, global types from dependent modules are not found

2 participants