Skip to content

Conversation

@danielroe
Copy link
Member

🔗 Linked issue

resolves #29757

📚 Description

This adds global type files registered with addTypeTemplate (in shared/nuxt contexts) so that Vue is aware of them for the purpose of resolving component props.

@bolt-new-by-stackblitz
Copy link

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 21, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: 7c28ad3

@coderabbitai
Copy link

coderabbitai bot commented Aug 21, 2025

Walkthrough

  • packages/kit/src/template.ts: Replaces adding the template.dst to prepare:types references with merging template.dst into nuxt.options.vite.vue.script.globalTypeFiles (via defu) so the Vue compiler sees the template as a global type file; condition now includes context.shared as well as no context and context.nuxt.
  • packages/kit/test/templates.spec.ts: Adds a Vitest that creates a fixture app.vue, registers a type template declaring a global type via addTypeTemplate, builds Nuxt, asserts the build succeeds, and closes Nuxt.
  • packages/nuxt/src/components/module.ts: Registers a new componentsDeclarationTemplate in addition to the existing componentsTypeTemplate.
  • packages/nuxt/src/components/templates.ts: Adds resolveComponentTypes helper; introduces componentsDeclarationTemplate to emit runtime-typed exports (components.d.ts); refactors componentsTypeTemplate to emit a Vue GlobalComponents augmentation in types/components.d.ts; adds hydration-related types and preserves island-aware logic.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 60aab3d and 7c28ad3.

📒 Files selected for processing (1)
  • packages/kit/test/templates.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/kit/test/templates.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: code
✨ 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/global-types

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 2

🧹 Nitpick comments (2)
packages/nuxt/src/components/templates.ts (1)

124-135: Minor: tighten LazyComponent generic constraint.
Constraining T to DefineComponent improves inference and prevents accidental widening when T is not a component type.

-type LazyComponent<T> = (T & DefineComponent<HydrationStrategies, {}, {}, {}, {}, {}, {}, { hydrated: () => void }>)
+type LazyComponent<T extends DefineComponent> = (T & DefineComponent<HydrationStrategies, {}, {}, {}, {}, {}, {}, { hydrated: () => void }>)
packages/kit/test/templates.spec.ts (1)

8-42: Great end-to-end coverage for the reported regression; consider adding a multi-template and shared-context case.

  • This test proves globalTypeFiles exposure for a single addTypeTemplate call. The common real-world case is multiple calls (from Nuxt core + modules) and shared-context templates.

You can extend the spec with an additional test to catch array-merging regressions and shared exposure:

 describe('addTypeTemplate', () => {
   it('should add type templates to vue global files', async () => {
@@
     await nuxt.close()
   })
+
+  it('should merge multiple global type files and support shared context', async () => {
+    const repoRoot = await findWorkspaceDir()
+    const rootDir = resolve(repoRoot, 'node_modules/.fixture', randomUUID())
+    await mkdir(rootDir, { recursive: true })
+    await writeFile(resolve(rootDir, 'app.vue'), `
+      <script setup lang="ts">
+      defineProps<FooProps>()
+      defineProps<BarProps>()
+      </script>
+      <template><div /></template>
+    `)
+    const nuxt = await loadNuxt({
+      cwd: rootDir,
+      overrides: {
+        modules: [
+          () => addTypeTemplate({
+            filename: 'foo.d.ts',
+            getContents: () => `
+              declare global { type FooProps = { a?: number } }
+              export {};
+            `,
+          }),
+          () => addTypeTemplate({
+            filename: 'bar.d.ts',
+            getContents: () => `
+              declare global { type BarProps = { b?: string } }
+              export {};
+            `,
+          }, { shared: true }),
+        ],
+      },
+    })
+    await expect(buildNuxt(nuxt)).resolves.not.toThrow()
+    await nuxt.close()
+  })
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d6ee30e and 60aab3d.

📒 Files selected for processing (4)
  • packages/kit/src/template.ts (1 hunks)
  • packages/kit/test/templates.spec.ts (1 hunks)
  • packages/nuxt/src/components/module.ts (2 hunks)
  • packages/nuxt/src/components/templates.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

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

Follow standard TypeScript conventions and best practices

Files:

  • packages/kit/test/templates.spec.ts
  • packages/nuxt/src/components/module.ts
  • packages/kit/src/template.ts
  • packages/nuxt/src/components/templates.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

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

Write unit tests for core functionality using vitest

Files:

  • packages/kit/test/templates.spec.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/*.vue : Use `<script setup lang="ts">` and the composition API when creating Vue components
📚 Learning: 2025-07-18T16:46:07.446Z
Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/*.{test,spec}.{ts,tsx,js,jsx} : Write unit tests for core functionality using `vitest`

Applied to files:

  • packages/kit/test/templates.spec.ts
📚 Learning: 2025-07-18T16:46:07.446Z
Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/e2e/**/*.{ts,js} : Write end-to-end tests using Playwright and `nuxt/test-utils`

Applied to files:

  • packages/kit/test/templates.spec.ts
📚 Learning: 2024-11-05T15:22:54.759Z
Learnt from: GalacticHypernova
PR: nuxt/nuxt#26468
File: packages/nuxt/src/components/plugins/loader.ts:24-24
Timestamp: 2024-11-05T15:22:54.759Z
Learning: In `packages/nuxt/src/components/plugins/loader.ts`, the references to `resolve` and `distDir` are legacy code from before Nuxt used the new unplugin VFS and will be removed.

Applied to files:

  • packages/nuxt/src/components/module.ts
  • packages/nuxt/src/components/templates.ts
🧬 Code graph analysis (2)
packages/kit/test/templates.spec.ts (1)
packages/kit/src/template.ts (1)
  • addTypeTemplate (71-113)
packages/nuxt/src/components/module.ts (2)
packages/kit/src/template.ts (1)
  • addTemplate (23-49)
packages/nuxt/src/components/templates.ts (1)
  • componentsDeclarationTemplate (136-152)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (6)
packages/nuxt/src/components/templates.ts (3)

4-4: Type-only import is correct and avoids runtime bundling.
Importing Nuxt types as type-only keeps the generated bundles clean.


154-174: Vue GlobalComponents augmentation looks good.

  • Module augmentation is scoped and ends with export {} to keep it as a module.
  • Mapping includes Lazy variants with LazyComponent.

135-153: Runtime export confirmed for componentNames
The componentNamesTemplate in packages/nuxt/src/components/templates.ts generates component-names.mjs with

export const componentNames = [ /* … */ ]

ensuring a runtime module exports componentNames.

The transform plugin in packages/nuxt/src/components/plugins/transform.ts injects this via Unimport’s virtual module #components, mapping

name: 'componentNames',
from: '#build/component-names',
virtualImports: ['#components']

so that any

import { componentNames } from '#components'

is rewritten to pull from component-names.mjs. No further changes are needed.

packages/nuxt/src/components/module.ts (2)

9-9: Importing componentsDeclarationTemplate is consistent with the new two-template split.
Keeps declarations and Vue augmentation concerns separated.


131-133: Order of template registration is sensible; one note on references.

  • components.d.ts is added via addTemplate (written to disk) and is resolved by the #components path mapping (set later in prepare:types), so it does not need an explicit reference entry.
  • types/components.d.ts uses addTypeTemplate so it’s referenced and participates in TS global augmentation. LGTM.

If you want extra safety, add an assertion in a unit test that importing from '#components' resolves types (e.g. a small TS program that imports a known component symbol and checks its type).

packages/kit/src/template.ts (1)

80-95: Retaining prepare:types references preserves editor TS awareness.
Good that references are still pushed for nuxt/node/shared contexts; this maintains compatibility with tooling that relies on TS triple-slash references.

Comment on lines +110 to +118
const componentTypes = app.components.filter(c => !c.island).map((c) => {
const type = `typeof ${genDynamicImport(isAbsolute(c.filePath)
? relative(buildDir, c.filePath).replace(NON_VUE_RE, '')
: c.filePath.replace(NON_VUE_RE, ''), { wrapper: false })}['${c.export}']`
const isServerOnly = c.mode === 'server' && c.filePath !== serverPlaceholderPath && !app.components.some(other => other.pascalName === c.pascalName && other.mode === 'client')
return [
c.pascalName,
isServerOnly ? `IslandComponent<${type}>` : type,
]
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential mismatch when identifying the server placeholder and unconditional IslandComponent usage.

  • Comparing c.filePath to serverPlaceholderPath by raw string can fail if one side has an added extension (e.g. .mjs) or differing normalisation, causing placeholders to be misclassified as “server-only”.
  • IslandComponent<…> is selected even when experimental.componentIslands is disabled, but the IslandComponent alias is only emitted when the flag is on. This can yield unresolved type references in projects with .server components and islands disabled.

Apply this diff to robustly compare placeholder paths and only use IslandComponent when islands are enabled:

 function resolveComponentTypes (nuxt: Nuxt, app: NuxtApp) {
   const buildDir = nuxt.options.buildDir
   const serverPlaceholderPath = resolve(distDir, 'app/components/server-placeholder')
   const componentTypes = app.components.filter(c => !c.island).map((c) => {
     const type = `typeof ${genDynamicImport(isAbsolute(c.filePath)
       ? relative(buildDir, c.filePath).replace(NON_VUE_RE, '')
       : c.filePath.replace(NON_VUE_RE, ''), { wrapper: false })}['${c.export}']`
-    const isServerOnly = c.mode === 'server' && c.filePath !== serverPlaceholderPath && !app.components.some(other => other.pascalName === c.pascalName && other.mode === 'client')
+    const stripExt = (p: string) => p.replace(/\.\w+$/, '')
+    const isServerOnly =
+      c.mode === 'server' &&
+      stripExt(c.filePath) !== stripExt(serverPlaceholderPath) &&
+      !app.components.some(other => other.pascalName === c.pascalName && other.mode === 'client')
     return [
       c.pascalName,
-      isServerOnly ? `IslandComponent<${type}>` : type,
+      (nuxt.options.experimental.componentIslands && isServerOnly) ? `IslandComponent<${type}>` : type,
     ]
   })
 
   return componentTypes
 }

@codspeed-hq
Copy link

codspeed-hq bot commented Aug 21, 2025

CodSpeed Performance Report

Merging #33026 will not alter performance

Comparing fix/global-types (7c28ad3) with main (d6ee30e)

Summary

✅ 10 untouched benchmarks

@danielroe danielroe merged commit 6501f62 into main Aug 25, 2025
116 of 120 checks passed
@danielroe danielroe deleted the fix/global-types branch August 25, 2025 08:39
@github-actions github-actions bot mentioned this pull request Aug 25, 2025
@github-actions github-actions bot mentioned this pull request Sep 2, 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.

Global types as generic type parameter in defineProps causing an exception

2 participants