Skip to content

fix(kit): try resolving module subpaths in resolveNuxtModule fn #32386

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

Merged
merged 5 commits into from
Jul 28, 2025

Conversation

DamianGlowala
Copy link
Member

🔗 Linked issue

resolves #32225

📚 Description

As much as there might be a better way to solve this, that's what I came up with so far - trying to resolve with subpaths one by one if original module name is not found.

Module in nuxt.config:
@nuxt/test-utils/module

Original resolved path:
<...>/node_modules/.pnpm/@nuxt+test-utils@3.19.1_@pl_14bfbf51f08bfde6e72d5192217ed19c/node_modules/@nuxt/test-utils/dist/module.mjs

Transformed path returned from resolveNuxtModule:
<...>/node_modules/.pnpm/@nuxt+test-utils@3.19.1_@pl_14bfbf51f08bfde6e72d5192217ed19c/node_modules/@nuxt/test-utils

@Copilot Copilot AI review requested due to automatic review settings June 13, 2025 10:19
@DamianGlowala DamianGlowala requested a review from danielroe as a code owner June 13, 2025 10:19
Copy link

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

Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR addresses module resolution for Nuxt by attempting to resolve subpaths when the original module name isn’t found.

  • Modified the iteration over module paths to allow for in-loop mutations.
  • Introduced a while loop to iteratively shorten the module path until a match is found.
Comments suppressed due to low confidence (1)

packages/kit/src/resolve.ts:115

  • Consider adding a comment explaining the purpose of iteratively shortening the module subpath. This will improve code understandability for future maintainers.
while (lastIndexOfPathInResolvedPath === -1 && path.includes('/')) {

@@ -104,12 +104,22 @@ export async function resolveNuxtModule (base: string, paths: string[]): Promise
const resolved: string[] = []
const resolver = createResolver(base)

for (const path of paths) {
for (let path of paths) {
Copy link
Preview

Copilot AI Jun 13, 2025

Choose a reason for hiding this comment

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

Consider using a separate temporary variable for the modified path instead of reassigning the loop variable. This can help prevent confusion and ensure that the original path value remains intact for any future reference.

Copilot generated this review using guidance from copilot-instructions.md.

Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

The resolveNuxtModule function was updated to enhance path resolution by first attempting to parse the resolved path as a node module path using parseNodeModulePath. If a directory is identified, it is directly added to the results; otherwise, the function falls back to slicing the resolved path by the last occurrence of the original path substring or uses the directory name if the substring is not found. This approach improves robustness over the previous substring slicing method. Additionally, test coverage for resolveNuxtModule was added to verify correct resolution of module paths. Other changes include refining module entry path collection and filtering in type generation and Nitro core code by preferring meta?.rawPath over entryPath, adjusting inclusion and exclusion patterns for runtime and distribution files, and expanding TypeScript include paths. No exported or public entity signatures were changed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ce7200 and b9d9136.

📒 Files selected for processing (1)
  • packages/kit/src/resolve.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/kit/src/resolve.test.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). (1)
  • 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/resolve-nuxt-modules

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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: 1

🧹 Nitpick comments (2)
packages/kit/src/resolve.ts (2)

107-110: Avoid hard-coded /index.ts – use path utilities for robustness

Splitting on the literal string '/index.ts' will mis-behave if:

  • the path ends with index.mjs / index.js
  • the file separator is \ (Windows)
  • index.ts appears in the middle of the string

Using pathe.dirname() (already imported) or a regexp keeps the logic portable and future-proof.

-      resolved.push(path.split('/index.ts')[0]!)
+      // Works for any extension and OS path separator
+      if (path.endsWith('.ts')) {
+        resolved.push(dirname(path))
+      } else {
+        resolved.push(path)
+      }

120-122: Possible duplicate entries in the result array

When multiple input paths resolve to the same directory (e.g. foo, foo/index.ts), the same string can be pushed repeatedly.
If the consumer expects uniqueness, wrap resolved in a Set or deduplicate before returning.

-  const resolved: string[] = []
+  const resolved = new Set<string>()-        resolved.push(resolvedPath.slice(0, lastIndexOfPathInResolvedPath + path.length))
+        resolved.add(resolvedPath.slice(0, lastIndexOfPathInResolvedPath + path.length))-  return resolved
+  return Array.from(resolved)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b56bb9 and c5c3f8b.

📒 Files selected for processing (1)
  • packages/kit/src/resolve.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: codeql (actions)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (1)
packages/kit/src/resolve.ts (1)

113-118: Path comparison is OS-sensitive – verify behaviour on Windows

String#lastIndexOf works on raw strings; Windows resolvedPath will contain back-slashes (\) whereas path uses forward-slashes. The loop will then never find a match.

If cross-platform support is required, normalise both to POSIX (pathe.toUnix) or to the platform separator before comparing.

Copy link

pkg-pr-new bot commented Jun 13, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: b9d9136

Copy link

codspeed-hq bot commented Jun 13, 2025

CodSpeed Performance Report

Merging #32386 will not alter performance

Comparing fix/resolve-nuxt-modules (b9d9136) with main (2313589)

Summary

✅ 10 untouched benchmarks

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5c3f8b and 8ce7200.

📒 Files selected for processing (4)
  • packages/kit/src/resolve.test.ts (2 hunks)
  • packages/kit/src/resolve.ts (2 hunks)
  • packages/kit/src/template.ts (2 hunks)
  • packages/nuxt/src/core/nitro.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/kit/src/resolve.ts
🧰 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/nuxt/src/core/nitro.ts
  • packages/kit/src/template.ts
  • packages/kit/src/resolve.test.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/src/resolve.test.ts
🧠 Learnings (4)
📓 Common learnings
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.
Learnt from: huang-julien
PR: nuxt/nuxt#29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In `packages/nuxt/src/app/components/nuxt-root.vue`, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

```js
const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null
```

instead of wrapping the import in a computed property or importing the component unconditionally.
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`
packages/nuxt/src/core/nitro.ts (5)

Learnt from: GalacticHypernova
PR: #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.

Learnt from: huang-julien
PR: #29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In packages/nuxt/src/app/components/nuxt-root.vue, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null

instead of wrapping the import in a computed property or importing the component unconditionally.

Learnt from: GalacticHypernova
PR: #29661
File: packages/kit/src/template.ts:227-229
Timestamp: 2024-11-28T21:22:40.496Z
Learning: In packages/kit/src/template.ts, when updating the EXTENSION_RE regular expression for TypeScript configuration, avoid using patterns like (\.\w+)+$ as they can result in catastrophic backtracking.

Learnt from: TheAlexLichter
PR: #31812
File: packages/nuxt/src/components/plugins/islands-transform.ts:202-202
Timestamp: 2025-04-18T18:33:41.753Z
Learning: In Nuxt, using rolldownVersion (not rollupVersion) is intentional when detecting if rolldown-vite is being used, even though TypeScript may show an error because the property isn't in standard type definitions yet.

Learnt from: Tofandel
PR: nuxt/nuxt#0
File: :0-0
Timestamp: 2024-11-11T12:34:22.648Z
Learning: Ensure that AI-generated summaries accurately reflect the key changes in the PR, focusing on notable changes such as the removal of unused imports and variables starting with underscores.

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

Learnt from: GalacticHypernova
PR: #29661
File: packages/kit/src/template.ts:227-229
Timestamp: 2024-11-28T21:22:40.496Z
Learning: In packages/kit/src/template.ts, when updating the EXTENSION_RE regular expression for TypeScript configuration, avoid using patterns like (\.\w+)+$ as they can result in catastrophic backtracking.

Learnt from: GalacticHypernova
PR: #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.

Learnt from: huang-julien
PR: #29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In packages/nuxt/src/app/components/nuxt-root.vue, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null

instead of wrapping the import in a computed property or importing the component unconditionally.

Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T16:46:07.446Z
Learning: Applies to **/*.{ts,tsx} : Follow standard TypeScript conventions and best practices

Learnt from: Tofandel
PR: nuxt/nuxt#0
File: :0-0
Timestamp: 2024-11-11T12:34:22.648Z
Learning: Ensure that AI-generated summaries accurately reflect the key changes in the PR, focusing on notable changes such as the removal of unused imports and variables starting with underscores.

packages/kit/src/resolve.test.ts (5)

Learnt from: GalacticHypernova
PR: #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.

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

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

Learnt from: GalacticHypernova
PR: #29661
File: packages/kit/src/template.ts:227-229
Timestamp: 2024-11-28T21:22:40.496Z
Learning: In packages/kit/src/template.ts, when updating the EXTENSION_RE regular expression for TypeScript configuration, avoid using patterns like (\.\w+)+$ as they can result in catastrophic backtracking.

Learnt from: huang-julien
PR: #29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In packages/nuxt/src/app/components/nuxt-root.vue, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null

instead of wrapping the import in a computed property or importing the component unconditionally.

🧬 Code Graph Analysis (2)
packages/nuxt/src/core/nitro.ts (1)
packages/kit/src/resolve.ts (1)
  • resolveNuxtModule (104-124)
packages/kit/src/resolve.test.ts (1)
packages/kit/src/resolve.ts (1)
  • resolveNuxtModule (104-124)
⏰ 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). (3)
  • GitHub Check: build
  • GitHub Check: code
  • GitHub Check: lint-docs
🔇 Additional comments (8)
packages/nuxt/src/core/nitro.ts (2)

49-57: LGTM! Enhanced module entry path collection.

The prioritisation of m.meta?.rawPath over m.entryPath provides more accurate module path information, which is essential for resolving module subpaths correctly. This change aligns with the PR objective to fix module subpath resolution issues.


152-158: LGTM! Improved TypeScript include coverage for modules.

The expansion to include both runtime/server and dist/runtime/server paths ensures comprehensive TypeScript coverage for different module structures and build outputs. The use of flatMap efficiently creates the required flat array structure.

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

276-280: LGTM! Consistent module entry path collection.

The logic mirrors the improvements in packages/nuxt/src/core/nitro.ts, prioritising m.meta?.rawPath over m.entryPath for more accurate module path information. The use of getDirectory(path) appropriately normalises paths to directories.


286-286: LGTM! Improved module path filtering.

The additional path.startsWith(rootDirWithSlash) condition appropriately narrows the scope to modules within the root directory, preventing external dependencies from being processed inappropriately in this context.


301-301: LGTM! Logical exclusion of dist files.

The addition of dist/*.* to the exclusion list appropriately prevents build artifacts from being included in type generation, maintaining consistency with the selective inclusion approach used elsewhere in the codebase.

packages/kit/src/resolve.test.ts (3)

1-1: LGTM! Appropriate test imports.

The new imports support the resolveNuxtModule test functionality: stat for directory validation, withTrailingSlash for consistent path formatting, and resolveNuxtModule for the function under test.

Also applies to: 4-4, 6-6


32-44: LGTM! Comprehensive test structure.

The test provides excellent coverage of the resolveNuxtModule function with appropriate use of inline snapshots for verification and clear assertions on the expected behaviour. The combination of installed modules plus an additional test module ensures thorough testing of the resolution logic.


46-49: LGTM! Thorough path validation.

The validation logic properly verifies that resolved paths are directories and end with the expected 'node_modules/' suffix. The error handling with .catch(() => false) ensures robust testing behaviour.

@danielroe danielroe merged commit 7f11348 into main Jul 28, 2025
81 of 83 checks passed
@danielroe danielroe deleted the fix/resolve-nuxt-modules branch July 28, 2025 16:24
@github-actions github-actions bot mentioned this pull request Jul 28, 2025
danielroe added a commit that referenced this pull request Jul 28, 2025
Co-authored-by: Daniel Roe <daniel@roe.dev>
@github-actions github-actions bot mentioned this pull request Jul 28, 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.

resolveNuxtModule fails for some modules
2 participants