Skip to content

feat(nuxt): scan named exports with addComponentExports #27155

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 10 commits into from
Apr 16, 2025

Conversation

huang-julien
Copy link
Member

@huang-julien huang-julien commented May 10, 2024

🔗 Linked issue

fix #25340

📚 Description

Hey 👋

This PR allows to have auto-imports for named components in ts/js/tsx/jsx files when using addComponentDir or with components/**

Copy link

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

@huang-julien huang-julien changed the title feat(nuxt): scanComponents named exports feat(nuxt): scan named exports with addComponentsDir May 13, 2024
@sadeghbarati
Copy link
Contributor

@danielroe Hi can you review this PR

This PR eliminates adding Nuxt module step in shadcn-vue Nuxt installation docs (shadcn-nuxt and manual tab)

Related issue in shadcn-vue

unovue/shadcn-vue#761

Copy link
Member

@danielroe danielroe left a comment

Choose a reason for hiding this comment

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

Sorry for the long delay in feedback on this.

I'm worried it would make component names less predictable (though up to be convinced otherwise). What about, to start with, a 'addComponentExports' kit utility that would take a file path/npm package that would then be scanned for named exports, which then get added automatically?

Copy link

coderabbitai bot commented Apr 15, 2025

Walkthrough

The changes introduce a new utility function, addComponentExports, which enables asynchronous resolution and registration of all named exports from a specified module file or npm package as components, with an optional prefix applied to their names. The component registration process is refactored: the existing addComponent function is simplified to normalise a single component and delegate to a new internal function, addComponents, which manages the addition of one or multiple components. The addComponents function centralises logic for merging components, handling priority checks, and managing name conflicts, issuing warnings when components with equal priority are overridden. The normalizeComponent function is refactored to focus solely on normalising and returning component objects, no longer handling registration. Imports for resolving module export names and paths are added to support these features. Public exports are updated to include addComponentExports, and a new test suite verifies the correct behaviour of this function, using a fixture file that provides both named and default Vue component exports.


📜 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 9a33ac6 and bce2f06.

📒 Files selected for processing (2)
  • packages/kit/test/components-fixture/Named.ts (1 hunks)
  • packages/kit/test/components.spec.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/kit/test/components-fixture/Named.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/kit/test/components.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

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

102-146: Good encapsulation of component creation logic.

The asynchronous getComponents function neatly centralises export handling, name resolution, and duplicate checks for each export. This approach should ensure robust scanning for multiple named exports across different file types.

Consider extracting this logic into a separate module for maintainability, especially as the codebase grows and more scanning features are added.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f514e3e and 4e89793.

📒 Files selected for processing (3)
  • packages/nuxt/src/components/scan.ts (3 hunks)
  • packages/nuxt/test/components-fixture/components/Named.ts (1 hunks)
  • packages/nuxt/test/scan-components.test.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/nuxt/src/components/scan.ts (4)
packages/schema/src/index.ts (1)
  • Component (3-3)
packages/nuxt/src/core/utils/index.ts (2)
  • resolveComponentNameSegments (1-1)
  • QUOTE_RE (18-18)
packages/nuxt/src/core/utils/names.ts (1)
  • resolveComponentNameSegments (20-45)
packages/nuxt/src/utils.ts (1)
  • logger (13-13)
🔇 Additional comments (4)
packages/nuxt/test/components-fixture/components/Named.ts (1)

1-13: Looks good overall.

This new file properly demonstrates both a default and a named export using defineComponent. No issues spotted with the syntax or logic.

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

84-91: Ensure consistent file naming logic.

When handling the file extension and constructing fileName, the code now consistently extracts fileExt using extname. Ensure this logic remains in sync with the newly supported .ts, .js, .tsx, and .jsx files, and that it gracefully handles edge cases (e.g., files lacking an extension).


168-177: Multi-export scanning looks solid.

Using resolveModuleExportNames for .ts, .js, .tsx, .jsx files is a clean approach for scanning multiple named exports. Automatically creating a component definition for each export is both convenient and user-friendly.

packages/nuxt/test/scan-components.test.ts (1)

52-55: Test coverage updates are excellent.

Including .ts in the extensions and updating the pattern ensures that TypeScript files are properly scanned. Adding two new components to the expectedComponents array verifies both the named and default exports from Named.ts.

Also applies to: 67-70, 81-86, 135-160

Copy link

pkg-pr-new bot commented Apr 15, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: bce2f06

Copy link

codspeed-hq bot commented Apr 15, 2025

CodSpeed Performance Report

Merging #27155 will not alter performance

Comparing feat/named_export_components (bce2f06) with main (4edb14c)

Summary

✅ 10 untouched benchmarks

@danielroe danielroe changed the title feat(nuxt): scan named exports with addComponentsDir feat(nuxt): scan named exports with addComponentExports Apr 15, 2025
@danielroe
Copy link
Member

oops, missed my suggestion. refactoring...

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 (3)
packages/kit/test/components.spec.ts (1)

39-75: Inline snapshot validation is thorough, but consider negative testing.

The inline snapshot coverage is a strong validation step for verifying registered components and key properties. It could be beneficial to add tests for edge cases, such as when no default export or named exports are present.

packages/kit/src/components.ts (2)

24-40: New addComponentExports function is clear and well-structured.

Registering named exports as components with optional prefix correctly integrates with components:dirs. This is an elegant solution, but consider error handling if resolveModuleExportNames yields an empty array.


50-76: Priority conflict logic is well-implemented, but watch for partial overrides.

The code warns when overriding components with equal priority, which preserves transparency. If partial overrides ever arise in edge cases, more nuanced handling might be needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4abf4a8 and 9a33ac6.

⛔ Files ignored due to path filters (2)
  • packages/kit/package.json is excluded by !**/package.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (6)
  • packages/kit/src/components.ts (3 hunks)
  • packages/kit/src/index.ts (1 hunks)
  • packages/kit/test/components.spec.ts (1 hunks)
  • packages/nuxt/src/app/components/nuxt-error-boundary.ts (2 hunks)
  • test/basic.test.ts (1 hunks)
  • test/fixtures/basic/pages/error/error-boundary.vue (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/kit/src/index.ts
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/basic.test.ts (1)
test/utils.ts (2)
  • renderPage (11-50)
  • expectNoClientErrors (52-64)
packages/kit/src/components.ts (2)
packages/kit/src/index.ts (6)
  • addComponentExports (19-19)
  • AddComponentOptions (20-20)
  • useNuxt (21-21)
  • resolvePath (28-28)
  • addComponent (19-19)
  • logger (32-32)
test/fixtures/basic/nuxt.config.ts (1)
  • components (237-243)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (13)
test/basic.test.ts (1)

1245-1251: Great addition of test coverage for error boundaries!

This test verifies that the NuxtErrorBoundary component correctly catches errors and renders fallback content without producing client-side errors. It's an essential test for ensuring error handling reliability, particularly during component failures at runtime.

test/fixtures/basic/pages/error/error-boundary.vue (2)

1-12: LGTM! Well-structured test fixture for error boundary testing.

This template correctly uses NuxtErrorBoundary with both the default and error slots, creating a proper test case for error handling.


14-24: Well-implemented broken component for testing.

The MyBrokenComponent is appropriately designed to trigger an error during the onMounted lifecycle hook, which is a realistic failure scenario for testing the error boundary functionality.

packages/nuxt/src/app/components/nuxt-error-boundary.ts (2)

3-3: Appropriate import for deferred error handling.

Adding the onNuxtReady import supports the new deferred error handling during hydration.


17-36: Excellent refactoring of error handling logic.

This refactoring significantly improves error handling during hydration:

  1. Moving useNuxtApp() inside the client-only block is more appropriate
  2. The handleError helper function effectively encapsulates error emission logic
  3. Different handling paths for hydration vs non-hydration states ensures errors don't disrupt the hydration process
  4. Deferring error handling until the app is ready during hydration is a more robust approach

This change makes the error boundary more reliable, especially during the critical hydration phase.

packages/kit/test/components.spec.ts (4)

1-4: Imports look good!

These foundational imports set up Vitest, Hookable, schema typing, and path utilities. They align well with project conventions.


6-17: Mock hooks and Nuxt instance are properly configured.

Defining mockHooks and mockNuxt ensures that tests run in isolation and correctly simulate Nuxt’s environment. This approach is both neat and maintainable.


19-23: Effective mocking of context references.

Mocking tryUseNuxt and useNuxt here allows for complete control over the Nuxt instance without side effects. This is a solid approach to isolating the tests from the actual Nuxt runtime.


25-38: Concise test logic setup.

The new test suite for addComponentExports is clear, with a properly prepared resolver and hook calls. This structure ensures readiness for subsequent test steps and fosters clarity of the tested functionality.

packages/kit/src/components.ts (4)

3-3: Importing from ‘mlly’ is correct.

Reliable resolution of export names ensures robust detection of named exports, aligning with the new scanning feature.


7-7: Importing resolvePath is well-chosen.

Leveraging resolvePath is a consistent approach which mirrors existing path resolution patterns within the Nuxt ecosystem.


45-47: addComponent remains simple and complements the new batch registration logic.

Delegating logic to normalizeComponent and addComponents ensures code reuse and maintainability.


78-100: normalizeComponent is consistent and uses defaults effectively.

The function ensures each component is assigned well-defined properties. The default mode detection from filename patterns is neatly handled.

@danielroe danielroe merged commit f906f89 into main Apr 16, 2025
47 checks passed
@danielroe danielroe deleted the feat/named_export_components branch April 16, 2025 08:58
@github-actions github-actions bot mentioned this pull request Apr 16, 2025
@danielroe
Copy link
Member

Merged this as a separate utility due to the potential performance overhead but I'd be very open to reconsidering when we have a *.[jt]s file in a components directory.

TheAlexLichter pushed a commit that referenced this pull request Apr 18, 2025
Co-authored-by: Daniel Roe <daniel@roe.dev>
danielroe added a commit that referenced this pull request Apr 23, 2025
Co-authored-by: Daniel Roe <daniel@roe.dev>
@github-actions github-actions bot mentioned this pull request Apr 23, 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.

Allow named exports in js/ts file with autoimport
5 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy