Skip to content

taro-cli新增支持可动态扩展ask导航步骤 #17715

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

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

Conversation

JiJiangYang
Copy link

@JiJiangYang JiJiangYang commented May 16, 2025

这个 PR 做了什么? (简要描述所做更改)
在使用自定义组件创建项目时,需要对项目在init过程中的导航进行扩展,例如:与"? 是否需要编译为 ES5 ?"类似的 "? 是否开启监控?"等。因此本次对taro-cli进行修改,实现外部组件可通过传参的方式传入自定义ask。

这个 PR 是什么类型? (至少选择一个)

  • 错误修复(Bugfix) issue: fix #
  • [*] 新功能(Feature)
  • 代码重构(Refactor)
  • TypeScript 类型定义修改(Typings)
  • 文档修改(Docs)
  • 代码风格更新(Code style update)
  • 其他,请描述(Other, please describe):

这个 PR 涉及以下平台:

  • 所有小程序
  • [*] 微信小程序
  • [*] 支付宝小程序
  • [*] 百度小程序
  • [*] 字节跳动小程序
  • QQ 轻应用
  • [*] 京东小程序
  • 快应用平台(QuickApp)
  • [*] Web 平台(H5)
  • 移动端(React-Native)
  • 鸿蒙(harmony)

Summary by CodeRabbit

  • 新功能
    • 为初始化命令新增了 --ask 参数,用于扩展脚手架的导航步骤,支持自定义交互流程。

Copy link

coderabbitai bot commented May 16, 2025

Walkthrough

本次更改为项目初始化流程引入了可扩展的自定义交互步骤。通过在项目配置接口中新增可选的 ask 函数属性,并在命令行 init 命令中加入 --ask 选项,实现了在模板选择后动态调用外部扩展逻辑的能力。

Changes

文件路径 变更摘要
packages/taro-cli/src/create/project.ts IProjectConf 接口新增可选 ask 函数属性;Project 类的 ask 方法在模板选择后,若存在 ask 函数则调用,传入当前配置和模板路径,异常被静默处理。
packages/taro-cli/src/presets/commands/init.ts init 命令新增 --ask [ask] 选项,并将其传递给 Project 构造函数,无其它控制流变化。

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Project

    User->>CLI: 执行 init 命令(可带 --ask 参数)
    CLI->>Project: 创建 Project 实例(传入 ask 选项)
    Project->>User: 交互式模板选择
    alt 存在 ask 函数
        Project->>ask: 调用 ask(conf, templatePath)
        ask-->>Project: 自定义交互逻辑完成
    end
    Project->>CLI: 初始化流程继续
Loading

Poem

🐇
新增参数 --ask,
让脚手架更灵活。
模板选完再发问,
扩展逻辑无所惧。
代码如兔跃,
创意随你加!

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

🧹 Nitpick comments (2)
packages/taro-cli/src/create/project.ts (2)

133-133: 未使用的变量

从对象中解构出ask变量后未使用它。虽然这是为了从other对象中排除ask属性,但仍会被静态分析工具标记为未使用变量。

你可以考虑使用TypeScript的类型系统来解决这个问题:

- const { ask, ...other } = conf
+ const other = { ...conf } as Omit<typeof conf, 'ask'>
+ delete other.ask

或者,如果想保持原来的解构方式,可以添加注释来抑制lint警告:

- const { ask, ...other } = conf
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { ask, ...other } = conf
🧰 Tools
🪛 ESLint

[error] 133-133: 'ask' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)


130-137: 考虑添加文档注释

建议为这个新增的导航步骤扩展功能添加JSDoc文档注释,说明这个功能的用途、参数和用法示例,这将有助于其他开发者理解和使用这个功能。

+/**
+ * 导航步骤扩展
+ * 允许外部组件通过ask函数传递自定义提示,实现额外的配置问题
+ * 例如:"是否需要编译为ES5?"或"是否开启监控?"等
+ * 
+ * @param {Object} config - 当前配置信息
+ * @param {string} config.templatePath - 选择的模板路径
+ * @returns {Promise<void>|void}
+ */
try {
  if (typeof conf.ask === 'function') {
🧰 Tools
🪛 ESLint

[error] 133-133: 'ask' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between edb74da and 229ad63.

📒 Files selected for processing (2)
  • packages/taro-cli/src/create/project.ts (2 hunks)
  • packages/taro-cli/src/presets/commands/init.ts (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/taro-cli/src/create/project.ts

[error] 46-46: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

🪛 ESLint
packages/taro-cli/src/create/project.ts

[error] 46-46: Don't use Function as a type. The Function type accepts any function-like value.
It provides no type safety when calling the function, which can be a common source of bugs.
It also accepts things like class declarations, which will throw at runtime as they will not be called with new.
If you are expecting the function to accept certain arguments, you should explicitly define the function shape.

(@typescript-eslint/ban-types)


[error] 133-133: 'ask' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

🔇 Additional comments (4)
packages/taro-cli/src/presets/commands/init.ts (3)

17-17: 新选项添加正确

此处成功添加了--ask [ask]命令行选项,并提供了适当的描述"扩展脚手架的导航步骤"。这符合PR的目标,即允许动态扩展初始化过程中的导航步骤。


38-38: 从选项中正确提取ask参数

正确地从命令行选项中提取了ask参数,以便后续传递给Project构造函数。


57-58: 成功将ask参数传递给Project构造函数

成功将css和ask参数传递给Project构造函数,使其可以在项目创建过程中使用。

packages/taro-cli/src/create/project.ts (1)

134-134:

❓ Verification inconclusive

确保调用模板参数是安全的

在调用外部ask函数时,确保传递的templatePath参数是有效的。当templateChoiceAnswer.template为空或未定义时可能会出现问题。


🏁 Script executed:

#!/bin/bash
# 检查 templatePath 的生成是否可能出现空值情况
ast-grep --pattern "this.templatePath($_)" | grep -v "//\|test"

Length of output: 213


以下脚本直接定位到 packages/taro-cli/src/create/project.ts,查看 templatePath 方法及其调用,确认是否存在未校验情况:

#!/bin/bash
# 定位 templatePath 方法定义
rg -n "templatePath" packages/taro-cli/src/create/project.ts

# 定位该方法的调用处
rg -n "this\.templatePath" packages/taro-cli/src/create/project.ts

下面运行脚本,定位 templatePath 方法定义及 templateChoiceAnswer 的来源,确认是否已对空或未定义的模板值做了校验:

#!/bin/bash
set -e

# 查找 templatePath 方法定义及上下文
rg -n -C3 "templatePath\s*\(" packages/taro-cli/src/create/project.ts

# 查找 templateChoiceAnswer 的赋值或来源
rg -n -C3 "templateChoiceAnswer" packages/taro-cli/src/create/project.ts

# 查找 ask 调用处,确认传入值是否有预校验
rg -n -C3 "conf\.ask" packages/taro-cli/src/create/project.ts

确保 templatePath 参数已校验

  • 文件:packages/taro-cli/src/create/project.ts 第 134 行
  • 场景:
    await conf.ask({ …other, templatePath: this.templatePath(templateChoiceAnswer.template) })
  • 风险:若 templateChoiceAnswer.template 为空或未定义,this.templatePath(undefined) 会导致路径拼装出错
  • 建议:在调用前对 templateChoiceAnswer.template 添加非空校验,例如:
    if (!templateChoiceAnswer.template) {
      throw new Error('请选择有效的模板');
    }
    await conf.ask({ …other, templatePath: this.templatePath(templateChoiceAnswer.template) });

@@ -43,6 +43,7 @@ export interface IProjectConf {
hideDefaultTemplate?: boolean
framework: FrameworkType
compiler?: CompilerType
ask?: Function
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

不要使用Function作为类型

避免使用Function作为类型声明,这无法提供类型安全性。建议定义具体的函数类型,明确指定参数和返回值类型。

-  ask?: Function
+  ask?: (config: Omit<IProjectConf, 'ask'> & { templatePath: string }) => Promise<void> | void
📝 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
ask?: Function
ask?: (config: Omit<IProjectConf, 'ask'> & { templatePath: string }) => Promise<void> | void
🧰 Tools
🪛 Biome (1.9.4)

[error] 46-46: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

🪛 ESLint

[error] 46-46: Don't use Function as a type. The Function type accepts any function-like value.
It provides no type safety when calling the function, which can be a common source of bugs.
It also accepts things like class declarations, which will throw at runtime as they will not be called with new.
If you are expecting the function to accept certain arguments, you should explicitly define the function shape.

(@typescript-eslint/ban-types)

🤖 Prompt for AI Agents
In packages/taro-cli/src/create/project.ts at line 46, replace the use of the
generic `Function` type for the `ask` property with a specific function type
that clearly defines the expected parameters and return type. This will improve
type safety by explicitly specifying what kind of function `ask` should be,
rather than using the broad and unsafe `Function` type.

Comment on lines +130 to +137
// 导航步骤扩展
try {
if (typeof conf.ask === 'function') {
const { ask, ...other } = conf
await conf.ask({ ...other, templatePath: this.templatePath(templateChoiceAnswer.template) })
}
} catch (e) { }

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

改进错误处理并确保类型安全

当前实现中有以下几个问题:

  1. 在try-catch块中静默忽略所有错误,这可能使调试变得困难
  2. 没有对ask函数的调用结果进行处理

建议改进错误处理并确保类型安全。

// 导航步骤扩展
try {
  if (typeof conf.ask === 'function') {
    const { ask, ...other } = conf
-    await conf.ask({ ...other, templatePath: this.templatePath(templateChoiceAnswer.template) })
+    await conf.ask({ ...other, templatePath: this.templatePath(templateChoiceAnswer.template) })
  }
-} catch (e) { }
+} catch (e) {
+  console.log(chalk.yellow('执行导航步骤扩展时发生错误: '), e)
+}
📝 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
// 导航步骤扩展
try {
if (typeof conf.ask === 'function') {
const { ask, ...other } = conf
await conf.ask({ ...other, templatePath: this.templatePath(templateChoiceAnswer.template) })
}
} catch (e) { }
// 导航步骤扩展
try {
if (typeof conf.ask === 'function') {
const { ask, ...other } = conf
await conf.ask({ ...other, templatePath: this.templatePath(templateChoiceAnswer.template) })
}
} catch (e) {
console.log(chalk.yellow('执行导航步骤扩展时发生错误: '), e)
}
🧰 Tools
🪛 ESLint

[error] 133-133: 'ask' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

🤖 Prompt for AI Agents
In packages/taro-cli/src/create/project.ts around lines 130 to 137, the current
try-catch block silently ignores all errors and does not handle the result of
the ask function. To fix this, add proper error logging or handling inside the
catch block to avoid silent failures, and ensure the call to conf.ask is awaited
and its result is handled or returned as appropriate. Also, add type checks or
assertions to guarantee type safety when calling conf.ask.

This was referenced May 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant