Skip to content
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

fix(nuxt): assign default name to component without setup #29869

Merged
merged 5 commits into from
Nov 12, 2024

Conversation

huang-julien
Copy link
Member

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

🔗 Linked issue

Fix #29843

📚 Description

Hi 👋 this PR adds __name if the component does not have a setup function.

Summary by CodeRabbit

  • New Features

    • Enhanced handling of component names for improved robustness.
    • New logic to support different scenarios based on the success of component name replacement.
  • Bug Fixes

    • Improved accuracy in identifying and replacing component names in various coding scenarios.

Copy link

stackblitz bot commented Nov 10, 2024

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

Copy link

coderabbitai bot commented Nov 10, 2024

Walkthrough

The pull request modifies the ComponentNamePlugin function in the component-names.ts file to improve the handling of component names in Nuxt. A new import from the acorn library is added, and the logic within the transform method is updated. The changes allow for parsing the input code to construct an Abstract Syntax Tree (AST) when a specific string (__name) is absent, enabling a more flexible approach to determining component names based on their export declarations.

Changes

File Path Change Summary
packages/nuxt/src/components/plugins/component-names.ts Modified ComponentNamePlugin to add Program import and enhance logic for component name handling.

Assessment against linked issues

Objective Addressed Explanation
Normalize component names when setup function is absent (#29843)

🐇 In the meadow where bunnies play,
Component names now shine bright as day!
With __name checked and AST in view,
PascalCase magic, for me and you!
Hopping along, our code’s now refined,
A joyful leap, with names intertwined! 🌼✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b52c2b0 and e305a30.

📒 Files selected for processing (1)
  • packages/nuxt/src/components/plugins/component-names.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nuxt/src/components/plugins/component-names.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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

🧹 Outside diff range and nitpick comments (1)
packages/nuxt/src/components/plugins/component-names.ts (1)

35-47: Consider adding tests for the new AST-based name injection

The changes introduce a new code path for handling components without __name. This should be covered by tests.

Would you like me to help create test cases for:

  1. Components without setup/__name
  2. Error handling scenarios
  3. Multiple export default edge case
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 506333f and b52c2b0.

📒 Files selected for processing (1)
  • packages/nuxt/src/components/plugins/component-names.ts (2 hunks)
🔇 Additional comments (3)
packages/nuxt/src/components/plugins/component-names.ts (3)

4-4: LGTM: Type import for AST handling

The addition of the Program type import from acorn is appropriate for type-safe AST manipulation.


36-40: LGTM: Existing name replacement logic

The handling of components with __name is maintained and works correctly, using a precise regex replacement.


35-47: Verify the impact on Vue Devtools display

The changes look good for injecting component names, but we should verify that this actually fixes the Vue Devtools display issue.

Let's check for any similar patterns in the codebase:

Comment on lines 41 to 47
const ast = this.parse(code) as Program
const exportDefault = ast.body.find(node => node.type === 'ExportDefaultDeclaration')
if (exportDefault) {
const { start, end } = exportDefault.declaration
s.overwrite(start, end, `Object.assign(${code.slice(start, end)}, { name: ${JSON.stringify(component.pascalName)} })`)
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for AST parsing and edge cases

While the AST-based approach is a good solution, there are some concerns:

  1. AST parsing could fail and should be handled gracefully
  2. The code assumes a single export default declaration
  3. Direct string manipulation with indices could be fragile

Consider applying this safer implementation:

-        const ast = this.parse(code) as Program
-        const exportDefault = ast.body.find(node => node.type === 'ExportDefaultDeclaration')
-        if (exportDefault) {
-          const { start, end } = exportDefault.declaration
-          s.overwrite(start, end, `Object.assign(${code.slice(start, end)}, { name: ${JSON.stringify(component.pascalName)} })`)
-        }
+        try {
+          const ast = this.parse(code) as Program
+          const exportDefaults = ast.body.filter(node => node.type === 'ExportDefaultDeclaration')
+          
+          if (exportDefaults.length > 1) {
+            console.warn(`Multiple export defaults found in ${id}, skipping name injection`)
+            return
+          }
+          
+          const exportDefault = exportDefaults[0]
+          if (exportDefault?.declaration) {
+            const { start, end } = exportDefault.declaration
+            const originalExport = code.slice(start, end)
+            s.overwrite(
+              start,
+              end,
+              `Object.assign(${originalExport}, { name: ${JSON.stringify(component.pascalName)} })`
+            )
+          }
+        } catch (error) {
+          console.warn(`Failed to parse ${id} for name injection:`, error)
+          return
+        }
📝 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
const ast = this.parse(code) as Program
const exportDefault = ast.body.find(node => node.type === 'ExportDefaultDeclaration')
if (exportDefault) {
const { start, end } = exportDefault.declaration
s.overwrite(start, end, `Object.assign(${code.slice(start, end)}, { name: ${JSON.stringify(component.pascalName)} })`)
}
}
try {
const ast = this.parse(code) as Program
const exportDefaults = ast.body.filter(node => node.type === 'ExportDefaultDeclaration')
if (exportDefaults.length > 1) {
console.warn(`Multiple export defaults found in ${id}, skipping name injection`)
return
}
const exportDefault = exportDefaults[0]
if (exportDefault?.declaration) {
const { start, end } = exportDefault.declaration
const originalExport = code.slice(start, end)
s.overwrite(
start,
end,
`Object.assign(${originalExport}, { name: ${JSON.stringify(component.pascalName)} })`
)
}
} catch (error) {
console.warn(`Failed to parse ${id} for name injection:`, error)
return
}

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

🧹 Outside diff range and nitpick comments (2)
packages/nuxt/src/components/plugins/component-names.ts (2)

36-39: Consider making the name replacement more robust

While the current implementation works, it could be more resilient to different code formatting styles.

Consider this more flexible approach:

-        const NAME_RE = new RegExp(`__name:\\s*['"]${filename}['"]`)
+        const NAME_RE = new RegExp(`__name:\\s*['"](${filename}|[^'"]*?)['"]`)

This would handle cases where the existing name might not exactly match the filename.


35-47: Consider unifying the component name injection strategy

The current implementation uses two different strategies (regex-based and AST-based) depending on the presence of __name. Consider using AST parsing consistently for both cases, which would:

  1. Provide more reliable code manipulation
  2. Make the code more maintainable
  3. Allow for better error handling

Would you like me to provide an example of a unified AST-based approach?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 506333f and b52c2b0.

📒 Files selected for processing (1)
  • packages/nuxt/src/components/plugins/component-names.ts (2 hunks)
🔇 Additional comments (2)
packages/nuxt/src/components/plugins/component-names.ts (2)

4-4: LGTM: Type import for AST parsing

The Program type import from acorn provides proper type safety for AST operations.


41-46: Critical: Add error handling and edge case protection

The AST-based transformation needs additional safety measures as highlighted in the previous review.

Let's verify potential edge cases in the codebase:

#!/bin/bash
# Description: Check for components with multiple export defaults or complex export patterns
# that might cause issues with the current implementation

# Look for files with multiple export default declarations
echo "Checking for multiple export defaults..."
rg "export\s+default" -A 2 -B 2

# Look for dynamic exports that might cause issues
echo "Checking for dynamic exports..."
ast-grep --pattern 'export default $$$'

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.

vue component names are not normalised without setup function
2 participants