Skip to content

fix(nitro): resolve paths pointing at bare module specifiers - #36011

Merged
danielroe merged 1 commit into
mainfrom
fix/nitro-specifiers
Aug 8, 2026
Merged

danielroe merged 1 commit into
mainfrom
fix/nitro-specifiers

Conversation

@danielroe

Copy link
Copy Markdown
Member

🔗 Linked issue

resolves #36003

📚 Description

this applies similar handling to the handling we do in @nuxt/kit for writing templates

@github-actions github-actions Bot added 5.x 🐛 bug Something isn't working as expected labels Aug 8, 2026
@pkg-pr-new

pkg-pr-new Bot commented Aug 8, 2026

Copy link
Copy Markdown

Open in StackBlitz

@nuxt/kit

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

@nuxt/nitro-server

npm i https://pkg.pr.new/@nuxt/nitro-server@36011

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: 1749ab8

@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Nitro alias generation now checks whether an alias target exists relative to basePath. If it does not exist, Nitro searches configured module directories using Nuxt-supported extensions. The resolved module path determines the generated wildcard TypeScript mapping. A Nuxt test configures an alias to the bare defu module and verifies that the generated #probe/defu path points into node_modules/defu.

Possibly related PRs

  • nuxt/nuxt#35233: Both PRs update TypeScript alias and path resolution for bare module specifiers.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the Nitro fix for resolving aliases that target bare module specifiers.
Description check ✅ Passed The description explains that Nitro should mirror @nuxt/kit handling for bare module specifiers, which matches the changeset.
Linked Issues check ✅ Passed The changes implement module resolution for bare Nitro aliases and add a test for generated tsconfig paths, satisfying issue #36003.
Out of Scope Changes check ✅ Passed The changes are limited to Nitro alias resolution and its loadNuxt test, with no unrelated modifications identified.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/nitro-specifiers

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
packages/nuxt/test/load-nuxt.test.ts (1)

193-209: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add a regression case for an unresolved bare specifier.

The test covers only successful defu resolution. It does not protect the required failure path. Add a deliberately missing alias and assert that tsConfigPaths retains the original module specifier.

Suggested regression case
             nuxt.options.nitro.alias ||= {}
             nuxt.options.nitro.alias['`#probe/defu`'] = 'defu'
+            nuxt.options.nitro.alias['`#probe/missing`'] = '__nuxt_missing_alias_probe__'
...
     expect(tsConfigPaths['`#probe/defu`']?.[0]?.replace(/\\/g, '/')).toMatch(/node_modules\/defu\//)
+    expect(tsConfigPaths['`#probe/missing`']).toEqual(['__nuxt_missing_alias_probe__'])

Based on the PR objectives, the test should cover both successful resolution and preservation after resolution failure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/nuxt/test/load-nuxt.test.ts` around lines 193 - 209, Add a second
Nitro alias in the existing `loadNuxt` regression test that points to a
deliberately nonexistent bare module specifier, then assert the corresponding
`tsConfigPaths` entry remains that original specifier when resolution fails.
Keep the existing `defu` assertion to cover successful resolution, so the test
validates both paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/nitro-server/src/index.ts`:
- Around line 801-817: Update the alias resolution flow around resolveModulePath
so unresolved aliases retain aliases[alias]! as absolutePath instead of the
initial basePath-resolved value. Only assign resolvedModule to absolutePath
after its stat succeeds; otherwise fall back to the original module specifier
before populating tsConfig.compilerOptions.paths[alias].

In `@packages/nuxt/test/load-nuxt.test.ts`:
- Around line 193-211: Wrap the assertion in the nitro alias test with a
try/finally block so the Nuxt instance created by loadNuxt is always closed.
Keep the existing assertion unchanged in the try block and move await
nuxt.close() into finally.

---

Nitpick comments:
In `@packages/nuxt/test/load-nuxt.test.ts`:
- Around line 193-209: Add a second Nitro alias in the existing `loadNuxt`
regression test that points to a deliberately nonexistent bare module specifier,
then assert the corresponding `tsConfigPaths` entry remains that original
specifier when resolution fails. Keep the existing `defu` assertion to cover
successful resolution, so the test validates both paths.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bbe5c389-3583-4fd4-aceb-edecc556fd99

📥 Commits

Reviewing files that changed from the base of the PR and between 5fd1ab0 and 1749ab8.

📒 Files selected for processing (2)
  • packages/nitro-server/src/index.ts
  • packages/nuxt/test/load-nuxt.test.ts

Comment on lines +801 to 817
let absolutePath = resolve(basePath, aliases[alias]!)
let stats = await fsp.stat(absolutePath).catch(() => null /* file does not exist */)
if (!stats) {
const resolvedModule = resolveModulePath(aliases[alias]!, {
try: true,
from: importPaths,
extensions: [...nuxt.options.extensions, '.d.ts', '.d.mts', '.d.cts'],
})
if (resolvedModule) {
absolutePath = resolvedModule
stats = await fsp.stat(resolvedModule).catch(() => null)
}
}

const isDirectory = aliases[alias]!.endsWith('/') || stats?.isDirectory()
// note - nitro will check + remove the file extension as required
tsConfig.compilerOptions.paths[alias] = [absolutePath]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve the original module specifier when resolution fails.

When resolveModulePath returns no result, absolutePath still contains resolve(basePath, aliases[alias]!). An alias such as #probe/missing: '__nuxt_missing_alias_probe__' is therefore emitted as a .nuxt path instead of the original module specifier. This can cause TS2307 or silently degrade imported types to any.

Set absolutePath to aliases[alias]! when no module resolves. Only use resolvedModule after its stat succeeds.

Suggested fallback
       if (resolvedModule) {
-        absolutePath = resolvedModule
-        stats = await fsp.stat(resolvedModule).catch(() => null)
+        const resolvedStats = await fsp.stat(resolvedModule).catch(() => null)
+        if (resolvedStats) {
+          absolutePath = resolvedModule
+          stats = resolvedStats
+        }
+      }
+      if (!stats) {
+        absolutePath = aliases[alias]!
       }

Based on the PR objectives, unresolved aliases must retain their original module specifier.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let absolutePath = resolve(basePath, aliases[alias]!)
let stats = await fsp.stat(absolutePath).catch(() => null /* file does not exist */)
if (!stats) {
const resolvedModule = resolveModulePath(aliases[alias]!, {
try: true,
from: importPaths,
extensions: [...nuxt.options.extensions, '.d.ts', '.d.mts', '.d.cts'],
})
if (resolvedModule) {
absolutePath = resolvedModule
stats = await fsp.stat(resolvedModule).catch(() => null)
}
}
const isDirectory = aliases[alias]!.endsWith('/') || stats?.isDirectory()
// note - nitro will check + remove the file extension as required
tsConfig.compilerOptions.paths[alias] = [absolutePath]
let absolutePath = resolve(basePath, aliases[alias]!)
let stats = await fsp.stat(absolutePath).catch(() => null /* file does not exist */)
if (!stats) {
const resolvedModule = resolveModulePath(aliases[alias]!, {
try: true,
from: importPaths,
extensions: [...nuxt.options.extensions, '.d.ts', '.d.mts', '.d.cts'],
})
if (resolvedModule) {
const resolvedStats = await fsp.stat(resolvedModule).catch(() => null)
if (resolvedStats) {
absolutePath = resolvedModule
stats = resolvedStats
}
}
if (!stats) {
absolutePath = aliases[alias]!
}
}
const isDirectory = aliases[alias]!.endsWith('/') || stats?.isDirectory()
// note - nitro will check + remove the file extension as required
tsConfig.compilerOptions.paths[alias] = [absolutePath]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/nitro-server/src/index.ts` around lines 801 - 817, Update the alias
resolution flow around resolveModulePath so unresolved aliases retain
aliases[alias]! as absolutePath instead of the initial basePath-resolved value.
Only assign resolvedModule to absolutePath after its stat succeeds; otherwise
fall back to the original module specifier before populating
tsConfig.compilerOptions.paths[alias].

Comment on lines +193 to +211
it('resolves nitro aliases pointing at bare module specifiers', async () => {
const nuxt = await loadNuxt({
cwd: repoRoot,
ready: true,
overrides: {
modules: [
(_options, nuxt) => {
nuxt.options.nitro.alias ||= {}
nuxt.options.nitro.alias['#probe/defu'] = 'defu'
},
],
},
})

const tsConfigPaths = (nuxt as any)._nitro?.options.typescript?.tsConfig?.compilerOptions?.paths ?? {}

expect(tsConfigPaths['#probe/defu']?.[0]?.replace(/\\/g, '/')).toMatch(/node_modules\/defu\//)

await nuxt.close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Close the Nuxt instance in a finally block.

await nuxt.close() runs only if the assertion succeeds. If the assertion fails, the ready: true load can leave resources open and affect later tests. Wrap the assertion in try/finally.

Suggested cleanup
-    const tsConfigPaths = (nuxt as any)._nitro?.options.typescript?.tsConfig?.compilerOptions?.paths ?? {}
-
-    expect(tsConfigPaths['`#probe/defu`']?.[0]?.replace(/\\/g, '/')).toMatch(/node_modules\/defu\//)
-
-    await nuxt.close()
+    try {
+      const tsConfigPaths = (nuxt as any)._nitro?.options.typescript?.tsConfig?.compilerOptions?.paths ?? {}
+      expect(tsConfigPaths['`#probe/defu`']?.[0]?.replace(/\\/g, '/')).toMatch(/node_modules\/defu\//)
+    } finally {
+      await nuxt.close()
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('resolves nitro aliases pointing at bare module specifiers', async () => {
const nuxt = await loadNuxt({
cwd: repoRoot,
ready: true,
overrides: {
modules: [
(_options, nuxt) => {
nuxt.options.nitro.alias ||= {}
nuxt.options.nitro.alias['#probe/defu'] = 'defu'
},
],
},
})
const tsConfigPaths = (nuxt as any)._nitro?.options.typescript?.tsConfig?.compilerOptions?.paths ?? {}
expect(tsConfigPaths['#probe/defu']?.[0]?.replace(/\\/g, '/')).toMatch(/node_modules\/defu\//)
await nuxt.close()
it('resolves nitro aliases pointing at bare module specifiers', async () => {
const nuxt = await loadNuxt({
cwd: repoRoot,
ready: true,
overrides: {
modules: [
(_options, nuxt) => {
nuxt.options.nitro.alias ||= {}
nuxt.options.nitro.alias['`#probe/defu`'] = 'defu'
},
],
},
})
try {
const tsConfigPaths = (nuxt as any)._nitro?.options.typescript?.tsConfig?.compilerOptions?.paths ?? {}
expect(tsConfigPaths['`#probe/defu`']?.[0]?.replace(/\\/g, '/')).toMatch(/node_modules\/defu\//)
} finally {
await nuxt.close()
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/nuxt/test/load-nuxt.test.ts` around lines 193 - 211, Wrap the
assertion in the nitro alias test with a try/finally block so the Nuxt instance
created by loadNuxt is always closed. Keep the existing assertion unchanged in
the try block and move await nuxt.close() into finally.

@codspeed

codspeed Bot commented Aug 8, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 21 untouched benchmarks
⏩ 3 skipped benchmarks1


Comparing fix/nitro-specifiers (1749ab8) with main (5fd1ab0)

Open in CodSpeed

Footnotes

  1. 3 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@danielroe
danielroe added this pull request to the merge queue Aug 8, 2026
Merged via the queue into main with commit 7b3b38a Aug 8, 2026
38 checks passed
@danielroe
danielroe deleted the fix/nitro-specifiers branch August 8, 2026 08:13
@github-actions github-actions Bot mentioned this pull request Aug 8, 2026
2 of 5 tasks
@github-actions github-actions Bot mentioned this pull request Aug 12, 2026
@github-actions github-actions Bot mentioned this pull request Aug 12, 2026
This was referenced Aug 25, 2026
@github-actions github-actions Bot mentioned this pull request Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

5.x 🐛 bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Nitro aliases with bare module specifiers become dangling paths entries in tsconfig.server.json

1 participant