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(auto-import-plugin): support functional components #2511

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

mengqiuleo
Copy link
Collaborator

@mengqiuleo mengqiuleo commented Nov 11, 2024

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: #2402

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Enhanced documentation for integrating the TinyVue component library with Vite and Webpack, including new examples for functional components.
    • Added global constants for TinyLoading, TinyModal, and TinyNotify to simplify usage across the application.
    • Introduced new configuration options for automatic imports in Vite and Webpack.
  • Improvements

    • Transitioned App.vue to use the Composition API for better state management and user interaction handling.
    • Updated Vite configuration to improve plugin integration and component auto-importing.
  • Dependency Updates

    • Upgraded @opentiny/vue and vite dependencies, and added unplugin-auto-import.

Copy link

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces significant updates to the integration documentation for the TinyVue component library with build tools like Vite and Webpack. Key changes include modifying the usage of TinyVueResolver to be invoked as a function, adding new sections on functional components, and updating configuration examples. Additionally, TypeScript declaration files are introduced for auto-imports and component types, enhancing global accessibility. The package.json file reflects updates to dependencies, and the App.vue file transitions to the Composition API, showcasing new functionalities and improved user interactions.

Changes

File Path Change Summary
examples/sites/demos/pc/webdoc/import-components.md Adjusted TinyVueResolver usage to function call; added section for functional components; updated Vite and Webpack examples.
internals/unplugin-tiny-vue/example/auto-imports.d.ts Added TypeScript declarations for global constants TinyLoading, TinyModal, and TinyNotify.
internals/unplugin-tiny-vue/example/components.d.ts Introduced module augmentation for Vue, adding types for RouterLink, RouterView, TinyButton, and TinyModal.
internals/unplugin-tiny-vue/example/package.json Updated @opentiny/vue and vite versions; added unplugin-auto-import dependency.
internals/unplugin-tiny-vue/example/src/App.vue Restructured template and script sections; transitioned to Composition API; added new reactive references and functions.
internals/unplugin-tiny-vue/example/vite.config.js Replaced autoImportPlugin with Components and AutoImport plugins; updated resolver configuration.
internals/unplugin-tiny-vue/src/index.ts Introduced TinyVueResolverOption interface; modified TinyVueResolver to accept options for auto-import.

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • zzcr

🐰 In the garden where TinyVue grows,
New configs and components, as everyone knows.
With buttons and modals, all set to play,
A hop and a skip, we brighten the day!
So let’s code together, in joyful delight,
With auto-imports, our future is bright! 🌼✨


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.

@github-actions github-actions bot added the bug Something isn't working label Nov 11, 2024
Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

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

🧹 Outside diff range and nitpick comments (7)
internals/unplugin-tiny-vue/example/package.json (1)

19-19: Consider updating Vite to a newer version

The current Vite version (4.3.8) is relatively old. Consider updating to the latest v4.x or v5.x for better performance and security.

-    "vite": "^4.3.8",
+    "vite": "^4.5.0",  # Latest v4
# or
+    "vite": "^5.0.0",  # Latest v5
internals/unplugin-tiny-vue/src/index.ts (2)

24-24: Consider adding type safety to the functional components array

To improve type safety and maintainability, consider defining a union type for the functional component names.

+type TinyVueFuncName = 'TinyModal' | 'TinyNotify' | 'TinyLoading';
-const TinyVueFunc = ['TinyModal', 'TinyNotify', 'TinyLoading']
+const TinyVueFunc: readonly TinyVueFuncName[] = ['TinyModal', 'TinyNotify', 'TinyLoading'] as const;

Line range hint 26-57: Well-designed plugin architecture with good separation of concerns

The implementation elegantly handles both functional and regular components while maintaining backward compatibility. The resolver pattern with options provides good extensibility for future enhancements.

A few architectural considerations:

  1. The separation between functional and regular components is clear and maintainable
  2. The option-based approach allows for future feature toggles
  3. The plugin structure remains compatible with multiple build tools
examples/sites/demos/pc/webdoc/import-components.md (2)

58-58: Document the breaking change in TinyVueResolver usage.

The change from TinyVueResolver to TinyVueResolver() appears to be a breaking change. Consider adding:

  1. A migration guide section
  2. A note explaining why this change was necessary
  3. The version where this change was introduced

Also applies to: 76-81


85-85: Enhance the functional components documentation.

Consider adding:

  1. Examples of how to use these components functionally
  2. Explanation of the autoImport: true option
  3. List of all available functional components
internals/unplugin-tiny-vue/example/src/App.vue (2)

34-36: Add null check for 'loadingInstance.value' in 'closeLoading' function

In the closeLoading function, loadingInstance.value might be null if the loading instance hasn't been initialized or has already been closed. This can lead to a runtime error.

Consider adding a null check:

 const closeLoading = () => {
+  if (loadingInstance.value) {
     loadingInstance.value.close()
+  }
 }

68-74: Check the value returned by 'TinyModal.confirm'

In the confirmClick function, the res parameter in the .then() callback may be a boolean value (true for confirm, false for cancel). Using it directly in the message might result in messages like "点击true按钮".

Consider mapping the response to a more user-friendly message:

 TinyModal.confirm('您确定要删除吗?').then((res) => {
   TinyNotify({
     type: 'info',
     title: '触发回调事件',
-    message: `点击${res}按钮`
+    message: `点击${res ? '确认' : '取消'}按钮`
   })
 })

This will display "点击确认按钮" or "点击取消按钮" based on the user's response.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a3e30c3 and 82e9184.

📒 Files selected for processing (7)
  • examples/sites/demos/pc/webdoc/import-components.md (2 hunks)
  • internals/unplugin-tiny-vue/example/auto-imports.d.ts (1 hunks)
  • internals/unplugin-tiny-vue/example/components.d.ts (1 hunks)
  • internals/unplugin-tiny-vue/example/package.json (1 hunks)
  • internals/unplugin-tiny-vue/example/src/App.vue (1 hunks)
  • internals/unplugin-tiny-vue/example/vite.config.js (1 hunks)
  • internals/unplugin-tiny-vue/src/index.ts (3 hunks)
✅ Files skipped from review due to trivial changes (2)
  • internals/unplugin-tiny-vue/example/auto-imports.d.ts
  • internals/unplugin-tiny-vue/example/components.d.ts
🔇 Additional comments (8)
internals/unplugin-tiny-vue/example/package.json (2)

18-18: Verify unplugin-auto-import compatibility

Since this PR focuses on auto-import functionality for functional components, we should verify the compatibility of unplugin-auto-import v0.18.3 with the current setup.

#!/bin/bash
# Description: Check compatibility of unplugin-auto-import with Vue and Vite versions

# Check if this version is used consistently
rg -g "package*.json" "unplugin-auto-import.*0\.18\.3"

# Check for any reported issues with functional components
gh api search/issues -X GET -f q="repo:antfu/unplugin-auto-import is:issue functional components vue3" --jq '.items[] | {title: .title, url: .html_url, state: .state}'

12-12: Verify compatibility with @opentiny/vue v3.18.0

The major version jump from 3.12 to 3.18 might introduce breaking changes.

internals/unplugin-tiny-vue/example/vite.config.js (1)

10-19: LGTM! Plugin configuration looks correct

The plugin configuration properly sets up both component and API auto-imports, which should fix the functional component support issue (#2402).

Let's verify the resolver configuration matches the documentation:

#!/bin/bash
# Check if the configuration matches the documentation
rg -A 5 "TinyVueResolver.*autoImport.*true" "examples/sites/demos/pc/webdoc/import-components.md"
internals/unplugin-tiny-vue/src/index.ts (3)

7-14: LGTM! Well-structured interface definition

The interface is well-documented and follows TypeScript best practices with clear JSDoc comments and explicit default value documentation.


57-57: Consider internationalizing the documentation comments

The plugin documentation comments are in Chinese. Consider using English for better international accessibility.

Let's verify plugin compatibility with different build tools:

#!/bin/bash
# Search for plugin usage patterns across different build configs
rg -t js -t ts "unplugin-tiny-vue" --glob "*config.{js,ts}"

26-42: Add explicit return type for better type safety

Consider adding an explicit return type to improve type safety and documentation.

-export const TinyVueResolver = (option: TinyVueResolverOption = {}) => {
+interface ComponentResolution {
+  name: string;
+  from: string;
+}
+
+export const TinyVueResolver = (option: TinyVueResolverOption = {}): ((componentName: string) => ComponentResolution | undefined) => {

Let's verify that existing usages of TinyVueResolver are compatible with the new signature:

internals/unplugin-tiny-vue/example/src/App.vue (2)

39-42: Ensure 'TinyLoading' is properly initialized

The TinyLoading.service method is used without explicitly importing TinyLoading. While auto-import is enabled, ensure that TinyLoading is correctly resolved by the auto-import plugin to prevent any runtime issues.

If necessary, confirm that TinyLoading is configured for auto-import.


58-61: Verify access to 'modal.vm.close()' in 'baseClick' function

When using modal.vm.close(), ensure that the vm property exists on the modal object returned by TinyModal.alert. If modal does not have a vm property, this will result in an error.

If the close method can be called directly, consider updating the code:

 function baseClick() {
   const modal = TinyModal.alert('基本提示框', '标题')
-  setTimeout(() => modal.vm.close(), 3000)
+  setTimeout(() => modal.close(), 3000)
 }

Otherwise, ensure that accessing modal.vm.close() is the correct approach according to the TinyModal API.

Comment on lines 4 to 6
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { TinyVueResolver } from '../dist/index.js'
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Build required: dist directory is missing and dependency setup needs attention

  • The dist directory is missing, indicating the plugin needs to be built before the example can work
  • unplugin-auto-import is missing from both dependencies and devDependencies
  • unplugin-vue-components is correctly added as a dependency

Please ensure to:

  1. Run the build process to generate the dist directory
  2. Add unplugin-auto-import as a dependency in package.json
🔗 Analysis chain

Verify dependencies and build requirements

The new imports look good, but let's ensure the build setup is complete.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the required packages are in dependencies
cat package.json | jq '.dependencies["unplugin-vue-components"], .dependencies["unplugin-auto-import"]'

# Verify if dist/index.js exists and is built
if [ -f "internals/unplugin-tiny-vue/dist/index.js" ]; then
    echo "dist/index.js exists"
else
    echo "Warning: dist/index.js not found. Build may be required."
fi

Length of output: 365


Script:

#!/bin/bash
# Check package.json in the specific plugin directory
cat internals/unplugin-tiny-vue/package.json | jq '.dependencies, .devDependencies'

# Check if the dist directory exists and list its contents
ls -la internals/unplugin-tiny-vue/dist/

# Find example usage of these plugins in the codebase
rg -l "unplugin-vue-components|unplugin-auto-import" internals/unplugin-tiny-vue/

Length of output: 752

Comment on lines 89 to 107
```js
// vite.config.js
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { TinyVueResolver } from '@opentiny/unplugin-tiny-vue'

module.exports = defineConfig({
configureWebpack: {
plugins: [
Components({
resolvers: [TinyVueResolver()]
}),
AutoImport({
resolvers: [TinyVueResolver({ autoImport: true })]
})
]
}
})
```
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Maintain consistency in configuration examples.

The Vite example uses export default while the Webpack example uses module.exports. Additionally, the Vite example incorrectly uses configureWebpack which is a Vue CLI concept, not a Vite concept.

Apply this diff to fix the Vite configuration:

// vite.config.js
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { TinyVueResolver } from '@opentiny/unplugin-tiny-vue'

-module.exports = defineConfig({
-  configureWebpack: {
-    plugins: [
+export default {
+  plugins: [
      Components({
        resolvers: [TinyVueResolver()]
      }),
      AutoImport({
        resolvers: [TinyVueResolver({ autoImport: true })]
      })
-    ]
-  }
-})
+  ]
+}

Also applies to: 111-124

</div>
<div class="content">
<span>消息模式:</span>
<tiny-button @click="messageClick"> 消息提示 </tiny-button>
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Undefined function 'messageClick' referenced in the template

The messageClick function is called in the template but is not defined in the script section. This will cause a runtime error when the button is clicked.

Apply this diff to add the missing messageClick function:

+function messageClick() {
+  TinyNotify({
+    type: 'info',
+    title: '消息提示',
+    message: '这是一个消息提示。',
+    position: 'top-right',
+    duration: 5000
+  })
+}

Committable suggestion skipped: line range outside the PR's diff.

@@ -73,7 +73,55 @@ module.exports = defineConfig({
configureWebpack: {
plugins: [
Components({
resolvers: [TinyVueResolver]
resolvers: [TinyVueResolver()]
Copy link
Collaborator

Choose a reason for hiding this comment

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

TinyVueResolver 从单层函数, 变成双层函数了。 对于已经使用该变量的项目来说, 是一个破坏性变更。

是不是可以通过新增一个导出变量,比如 TinyVueAutoImportor 的变量呢?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

已修复,通过新增导出变量解决

@mengqiuleo mengqiuleo force-pushed the fix-auto-import-plugin branch from 82e9184 to 7a2bd2e Compare November 27, 2024 10:49
}
}

export const TinyVueResolver = (componentName: string) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

为了避免破坏性变更, 你是保留了 TinyVueResolver 的名字, 特意新加了一个TinyVueAutoImportResolver 变量。

但现在看来, TinyVueAutoImportResolver 变量的能力涵盖了 TinyVueResolver, 且都是一层函数了
建议:只导出 TinyVueResolver变量, 但它的能力是 上面函数的能力即可。

configureWebpack: {
plugins: [
Components({
resolvers: [TinyVueAutoImportResolver]
Copy link
Collaborator

Choose a reason for hiding this comment

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

这两个变量,都还使用 TinyVueResolver 这个名称即可

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

已修复. PTAL

@mengqiuleo mengqiuleo force-pushed the fix-auto-import-plugin branch from 7a2bd2e to 0c5e771 Compare December 7, 2024 01:02
import autoImportPlugin from '../dist/index.js'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { TinyVueAutoImportResolver } from '../dist/index.js'
Copy link
Collaborator

Choose a reason for hiding this comment

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

这里的名称又漏改为 TinyVueResolver了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants