Skip to content

feat(api-babel): 支持Taro.xx.yy形式的api treeshaking#18848

Open
tutuxxx wants to merge 3 commits intomainfrom
feat/api_shaking
Open

feat(api-babel): 支持Taro.xx.yy形式的api treeshaking#18848
tutuxxx wants to merge 3 commits intomainfrom
feat/api_shaking

Conversation

@tutuxxx
Copy link
Copy Markdown
Member

@tutuxxx tutuxxx commented Feb 4, 2026

这个 PR 做了什么? (简要描述所做更改)

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

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

这个 PR 涉及以下平台:

  • 所有平台
  • [ ✅] Web 端(H5)
  • 移动端(React-Native)
  • 鸿蒙(Harmony)
  • 鸿蒙容器(Harmony Hybrid)
  • ASCF 元服务
  • 快应用(QuickApp)
  • 所有小程序
  • 微信小程序
  • 企业微信小程序
  • 京东小程序
  • 百度小程序
  • 支付宝小程序
  • 支付宝 IOT 小程序
  • 钉钉小程序
  • QQ 小程序
  • 飞书小程序
  • 快手小程序
  • 头条小程序

Summary by CodeRabbit

发布说明

  • 新功能

    • 优化了对 Taro 命名空间式 API 的处理与抽离,提升代码打包和 Tree-shaking 效果。
  • 其他更新

    • 将整体版本提升为 4.1.12-alpha.1(测试版),若干包的发布元数据已同步为此预发布版本。

@tutuxxx tutuxxx added this to the 4.1.12 milestone Feb 4, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 4, 2026

Walkthrough

此PR 将大量 package.json 的版本从 4.1.11 升级到 4.1.12-alpha.1,并在 packages/babel-plugin-transform-taroapi/src/index.ts 中新增/扩展对 Taro 命名空间(Taro.xx.yy)形式的识别与树摇重写逻辑(含对 TS cast 与可选链的处理)。

Changes

Cohort / File(s) Summary
根与原生绑定包
package.json, crates/native_binding/package.json, npm/darwin-arm64/package.json, npm/darwin-x64/package.json, npm/linux-arm64-gnu/package.json, npm/linux-x64-gnu/package.json, npm/linux-x64-musl/package.json, npm/win32-x64-msvc/package.json
统一将版本字段从 4.1.114.1.12-alpha.1(元数据变更)。
Babel 插件与源码变更
packages/babel-plugin-transform-taroapi/package.json, packages/babel-plugin-transform-taroapi/src/index.ts, packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/package.json, packages/babel-plugin-transform-solid-jsx/package.json, packages/babel-preset-taro/package.json
多处 package.json 版本升级;src/index.ts 新增 stripTSCast,扩展对 Taro.xx.yy(含可选链/TS cast)的 MemberExpression 与 CallExpression 重写与树摇处理,并修正赋值判断中的节点引用。
工具链 / 构建 / 规范类包
packages/create-app/package.json, packages/css-to-react-native/package.json, packages/eslint-config-taro/package.json, packages/eslint-plugin-taro/package.json, packages/jest-helper/package.json, packages/postcss-html-transform/package.json, packages/postcss-plugin-constparse/package.json, packages/postcss-pxtransform/package.json, packages/postcss-unit-transform/package.json, packages/rollup-plugin-copy/package.json, packages/shared/package.json, packages/stylelint-config-taro-rn/package.json, packages/stylelint-taro-rn/package.json, packages/stylelint-taro/package.json
版本字段统一升级(仅 metadata 修改)。
核心框架与运行时
packages/taro-api/package.json, packages/taro-extend/package.json, packages/taro-framework-react/package.json, packages/taro-framework-solid/package.json, packages/taro-framework-vue3/package.json, packages/taro-h5/package.json, packages/taro-helper/package.json, packages/taro-loader/package.json, packages/taro-react/package.json, packages/taro-rn/package.json, packages/taro-router/package.json, packages/taro-router-rn/package.json, packages/taro-runtime/package.json, packages/taro-runtime-rn/package.json, packages/taro-service/package.json, packages/taro/package.json
版本字段统一升级(仅 metadata 修改)。
平台支持与组件库
packages/taro-platform-*/*.json, packages/taro-components*.package.json, packages/taro-components-library-*/*.json, packages/taro-components-rn/package.json, packages/taro-components-react/package.json
多平台与组件库包版本升级到 4.1.12-alpha.1
插件与 runner / transformer 系列
packages/taro-plugin-*/package.json, packages/taro-rn-runner/package.json, packages/taro-rn-style-transformer/package.json, packages/taro-rn-supporter/package.json, packages/taro-rn-transformer/package.json, packages/taro-runner-utils/package.json, packages/taro-transformer-wx/package.json, packages/taro-vite-runner/package.json, packages/taro-webpack5-*/package.json, packages/taro-with-weapp/package.json, packages/taroize/package.json
插件与运行器/转换器系列包版本统一升级(仅 package.json 版本字段变更)。

Sequence Diagram(s)

(无序列图 — 变更未满足生成时需的多角色顺序交互条件)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • luckyadam
  • yoyo837
  • Single-Dancer

🐰 新版跳跃到山巅,
树摇细语拆冗言,
命名空间更聪明,
六十包齐步先,
Alpha 花开正当年。

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 拉取请求标题准确描述了主要变更:为Babel插件添加了对Taro.xx.yy形式API树摇动的支持。标题简洁明确,反映了最重要的功能改进。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/api_shaking

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov bot commented Feb 4, 2026

Codecov Report

❌ Patch coverage is 39.62264% with 32 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.26%. Comparing base (3317bb2) to head (3f1caf6).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...ckages/babel-plugin-transform-taroapi/src/index.ts 39.62% 20 Missing and 12 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #18848      +/-   ##
==========================================
- Coverage   56.31%   56.26%   -0.05%     
==========================================
  Files         447      447              
  Lines       23352    23399      +47     
  Branches     5776     5800      +24     
==========================================
+ Hits        13150    13165      +15     
- Misses       8372     8394      +22     
- Partials     1830     1840      +10     
Flag Coverage Δ
taro-cli 72.85% <ø> (ø)
taro-runtime 60.27% <ø> (ø)
taro-web 53.12% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ckages/babel-plugin-transform-taroapi/src/index.ts 75.88% <39.62%> (-16.81%) ⬇️

... and 7 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This was referenced Feb 7, 2026
Copy link
Copy Markdown

@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 (1)
packages/babel-plugin-transform-taroapi/src/index.ts (1)

134-143: 建议抽取 flatName 到本地标识符的复用逻辑

Line [134]-Line [143] 与 Line [205]-Line [212] 的 invokedApis 查找/创建逻辑完全重复。建议提取 helper,避免后续两个分支行为漂移。

Also applies to: 205-212

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/babel-plugin-transform-taroapi/src/index.ts` around lines 134 - 143,
The logic that builds flatName and looks up/creates an entry in invokedApis is
duplicated; extract it into a small helper (e.g.,
getOrCreateInvokedApiIdentifier) that accepts the computed flatName (from
namespaceName and methodName), the current ast scope (for generateUid), and
invokedApis, then returns the generated identifier name or existing one; replace
the duplicated blocks around flatName/this.apis checks (the code using flatName,
invokedApis.has, ast.scope.generateUid, invokedApis.set, and t.identifier) at
both locations (the block using namespaceName/methodName and the similar block
at lines ~205-212) with calls to that helper to ensure single-point behavior and
avoid drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/babel-plugin-transform-taroapi/src/index.ts`:
- Around line 125-150: The current transformation in the block that computes
isCalleeOfCall and then rewrites nested namespace member expressions (using
stripTSCast, invokedApis, this.apis and ast.replaceWith) lacks protection
against being the left-hand side of an assignment, so expressions like
Taro.xx.yy = fn get wrongly rewritten; add an isAssignmentLHS guard (similar to
the existing protection used for single-level Taro.xxx) by detecting when
ast.parent is an AssignmentExpression (or OptionalAssignment if applicable) and
ast.parent.left === node and skip the rewrite when true.

---

Nitpick comments:
In `@packages/babel-plugin-transform-taroapi/src/index.ts`:
- Around line 134-143: The logic that builds flatName and looks up/creates an
entry in invokedApis is duplicated; extract it into a small helper (e.g.,
getOrCreateInvokedApiIdentifier) that accepts the computed flatName (from
namespaceName and methodName), the current ast scope (for generateUid), and
invokedApis, then returns the generated identifier name or existing one; replace
the duplicated blocks around flatName/this.apis checks (the code using flatName,
invokedApis.has, ast.scope.generateUid, invokedApis.set, and t.identifier) at
both locations (the block using namespaceName/methodName and the similar block
at lines ~205-212) with calls to that helper to ensure single-point behavior and
avoid drift.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb5f4d6 and 3f1caf6.

📒 Files selected for processing (1)
  • packages/babel-plugin-transform-taroapi/src/index.ts

Comment on lines +125 to +150
const isCalleeOfCall = (t.isCallExpression(ast.parent) || t.isOptionalCallExpression(ast.parent)) && (ast.parent as any).callee === node
if (!isCalleeOfCall) {
const innerObj = stripTSCast(node.object)
if (t.isMemberExpression(innerObj) || t.isOptionalMemberExpression(innerObj)) {
const isTaroNamespace = t.isIdentifier(innerObj.object, { name: taroName })
if (isTaroNamespace) {
const namespaceName = t.isIdentifier(innerObj.property) ? innerObj.property.name : (t.isStringLiteral(innerObj.property) ? innerObj.property.value : null)
const methodName = t.isIdentifier(node.property) ? node.property.name : (t.isStringLiteral(node.property) ? node.property.value : null)
if (namespaceName && methodName) {
const flatName = `${namespaceName}_${methodName}`
if (this.apis.has(flatName)) {
let identifier: BabelCore.types.Identifier
if (invokedApis.has(flatName)) {
identifier = t.identifier(invokedApis.get(flatName)!)
} else {
const newName = ast.scope.generateUid(flatName)
invokedApis.set(flatName, newName)
identifier = t.identifier(newName)
}
ast.replaceWith(identifier as any)
return
}
}
}
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, let's find and examine the target file
find . -type f -name "index.ts" -path "*/babel-plugin-transform-taroapi/src/*" | head -5

Repository: NervJS/taro

Length of output: 109


🏁 Script executed:

# Read the file to see the context around lines 125-150 and 171
cat -n packages/babel-plugin-transform-taroapi/src/index.ts | sed -n '100,200p'

Repository: NervJS/taro

Length of output: 5262


🏁 Script executed:

# Get the total line count to ensure we're looking at the right file
wc -l packages/babel-plugin-transform-taroapi/src/index.ts

Repository: NervJS/taro

Length of output: 111


🏁 Script executed:

# Check the exact context around line 171 to understand the assignment protection pattern
cat -n packages/babel-plugin-transform-taroapi/src/index.ts | sed -n '168,185p'

Repository: NervJS/taro

Length of output: 966


🏁 Script executed:

# Search for other assignment-related checks in the file
rg -n "isAssignment|AssignmentExpression" packages/babel-plugin-transform-taroapi/src/index.ts

Repository: NervJS/taro

Length of output: 273


🏁 Script executed:

# Let's check what happens in the CallExpression handler to see if there's additional protection there
cat -n packages/babel-plugin-transform-taroapi/src/index.ts | sed -n '189,230p'

Repository: NervJS/taro

Length of output: 2456


🏁 Script executed:

# Check if there's any parent checking for the first MemberExpression handler (lines 125-150)
cat -n packages/babel-plugin-transform-taroapi/src/index.ts | sed -n '120,155p'

Repository: NervJS/taro

Length of output: 2200


缺少赋值左值保护,会产生非法重写

第 126-145 行的处理逻辑缺少对赋值表达式左值的保护。当源码为 Taro.xx.yy = fn 时,会被错误地改写为 imported_id = fn,造成语法错误或运行时异常。第 171 行已有对单层命名空间 Taro.xxx 的正确保护,应对嵌套命名空间采用一致的防护措施。

建议在第 126 行添加 isAssignmentLHS 检查,参考如下:

🔧 建议修复
       'MemberExpression|OptionalMemberExpression' (ast: BabelCore.NodePath<any>) {
         const node = ast.node

         // 处理两层命名空间属性访问:Taro.xx.yy / Taro?.xx?.yy(非调用场景)
         // 调用场景由 CallExpression|OptionalCallExpression 负责
         const isCalleeOfCall = (t.isCallExpression(ast.parent) || t.isOptionalCallExpression(ast.parent)) && (ast.parent as any).callee === node
-        if (!isCalleeOfCall) {
+        const isAssignmentLHS = t.isAssignmentExpression(ast.parent) && ast.parent.left === node
+        if (!isCalleeOfCall && !isAssignmentLHS) {
           const innerObj = stripTSCast(node.object)
           if (t.isMemberExpression(innerObj) || t.isOptionalMemberExpression(innerObj)) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/babel-plugin-transform-taroapi/src/index.ts` around lines 125 - 150,
The current transformation in the block that computes isCalleeOfCall and then
rewrites nested namespace member expressions (using stripTSCast, invokedApis,
this.apis and ast.replaceWith) lacks protection against being the left-hand side
of an assignment, so expressions like Taro.xx.yy = fn get wrongly rewritten; add
an isAssignmentLHS guard (similar to the existing protection used for
single-level Taro.xxx) by detecting when ast.parent is an AssignmentExpression
(or OptionalAssignment if applicable) and ast.parent.left === node and skip the
rewrite when true.

This was referenced Mar 7, 2026
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