Skip to content

revert(harmony): 还原 inject 插件对平台基类的错误引用#18326

Merged
ZakaryCode merged 2 commits intomainfrom
fix/harmony-inject-env
Sep 19, 2025
Merged

revert(harmony): 还原 inject 插件对平台基类的错误引用#18326
ZakaryCode merged 2 commits intomainfrom
fix/harmony-inject-env

Conversation

@ZakaryCode
Copy link
Copy Markdown
Contributor

@ZakaryCode ZakaryCode commented Sep 8, 2025

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

还原 inject 插件对平台基类的错误引用

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

  • 错误修复 (Bugfix) issue: fix #

这个 PR 涉及以下平台:

  • 鸿蒙(Harmony)

Summary by CodeRabbit

  • 新特性

  • 重构

    • 调整内部环境注入插件的上下文绑定方式,统一通过 this 访问配置与上下文,提升可维护性。
  • 影响

    • 无用户可见变更;现有功能、配置与构建流程保持不变。

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Sep 8, 2025

Walkthrough

inject-env.ts 中默认导出函数由接收 platform 参数改为使用显式的 this: Harmony 绑定;在内部引入 that 作为 this 的别名,并把原先对 platform.getConfig()platform.context.runnerUtils 的访问改为通过 that 访问。其余插件逻辑未变。

Changes

Cohort / File(s) Summary of edits
Vite 插件 this 绑定重构
packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts
函数签名由 function (platform: Harmony) 改为 function (this: Harmony);新增本地别名 that;将 platform.getConfig()platform.context.runnerUtils 等调用替换为 that.getConfig()that.context.runnerUtils;无其他逻辑变更。

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • yoturg

Poem

兔爪轻点换了个“this”的帽,
不再喊平台名,改叫“that”来报到。
配置与工具乖乖随行跑,
逻辑如旧,风吹草不摇。
编译风顺耳,胡萝卜香到笑 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/harmony-inject-env

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.

@ZakaryCode ZakaryCode added the T-harmony Target - 编译到 Harmony label Sep 8, 2025
@ZakaryCode ZakaryCode added this to 4.x Sep 8, 2025
@ZakaryCode ZakaryCode added this to the 4.1.7 milestone Sep 8, 2025
@ZakaryCode ZakaryCode requested a review from tutuxxx September 8, 2025 03:30
@coderabbitai coderabbitai Bot requested a review from yoturg September 8, 2025 03:30
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 (4)
packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts (4)

12-12: 对 businessId 去引号没问题,顺手 trim 更稳妥

某些配置可能带空白符,建议在 replace 前先 trim,避免注入空格。

-  const businessId = that.getConfig().defineConstants?.LOCATION_APIKEY?.replace(/^['"]|['"]$/g, '')
+  const businessId = that.getConfig().defineConstants?.LOCATION_APIKEY?.trim()?.replace(/^['"]|['"]$/g, '')

18-20: 对 runnerUtils 的解构建议加防御并给出明确错误

在极端/初始化顺序异常场景下,that.contextrunnerUtils 可能为空,直接解构会抛错。建议先判空并通过 Vite 上下文报错,定位更清晰。

-      const { runnerUtils } = that.context
-      const { getViteHarmonyCompilerContext } = runnerUtils
+      const runnerUtils = that.context?.runnerUtils
+      if (!runnerUtils) {
+        pluginContext.error('[taro:harmony] runnerUtils 不可用:无法获取编译上下文')
+        return null
+      }
+      const { getViteHarmonyCompilerContext } = runnerUtils

70-79: DRY:抽取注入 businessId 的重复逻辑,降低维护风险

CallExpressionMemberExpression 分支的注入代码基本重复。建议提取成局部助手函数,后续调整(如变更 key 名或校验策略)不易跑偏。

应用于本段的局部替换示例:

-                    if (!hasBusinessId) {
-                      if (!businessId) {
-                        console.warn(`Error: 使用定位相关 API(${path.node.callee.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`)
-                        return
-                      }
-                      args.properties.push(
-                        t.objectProperty(t.identifier('businessId'), t.stringLiteral(businessId))
-                      )
-                    }
+                    ensureBusinessId(args, path.node.callee.name, t)
-                          if (!hasBusinessId) {
-                            if (!businessId) {
-                              console.warn(`Error: 使用定位相关 API(${path.node.property.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`)
-                              return
-                            }
-                            args.properties.push(
-                              t.objectProperty(t.identifier('businessId'), t.stringLiteral(businessId))
-                            )
-                          }
+                          ensureBusinessId(args, path.node.property.name, t)

在文件较前位置(与 businessId 同作用域)新增助手函数:

function ensureBusinessId(args: BabelCore.types.ObjectExpression, apiName: string, t: typeof BabelCore.types) {
  const hasBusinessId = args.properties.some(
    prop => !t.isSpreadElement(prop) && t.isIdentifier((prop as any).key) && (prop as any).key.name === 'businessId'
  )
  if (!hasBusinessId) {
    if (!businessId) {
      console.warn(`Error: 使用定位相关 API(${apiName}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`)
      return
    }
    args.properties.push(t.objectProperty(t.identifier('businessId'), t.stringLiteral(businessId)))
  }
}

Also applies to: 94-102


8-9: 命名微调建议:that → platform,可读性更强

that = this 没问题,但用 platform 更直接表达语义,易于维护。

-  const that = this
+  const platform = this

(同步更新后续 that.* 引用)

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1676906 and 8207493.

📒 Files selected for processing (1)
  • packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Build Rust Binding / stable - aarch64-apple-darwin
  • GitHub Check: Build Rust Binding / stable - x86_64-apple-darwin
  • GitHub Check: Build Rust Binding / stable - x86_64-pc-windows-msvc
  • GitHub Check: Build Rust Binding / stable - x86_64-pc-windows-msvc
🔇 Additional comments (1)
packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts (1)

8-9: inject-env 已正确使用 .call(this, opt) 绑定 this,无需调整

const { runnerUtils } = that.context
const { getViteHarmonyCompilerContext } = runnerUtils
const compiler = getViteHarmonyCompilerContext(pluginContext)
const exts = Array.from(new Set(compiler?.frameworkExts.concat(SCRIPT_EXT)))
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

潜在崩溃:compiler?.frameworkExts 可能为 undefined,直接 concat 会抛异常

compilerundefined 或未提供 frameworkExts 时,undefined.concat(...) 会直接中断构建。建议使用空数组回退。

-      const exts = Array.from(new Set(compiler?.frameworkExts.concat(SCRIPT_EXT)))
+      const exts = Array.from(new Set([...(compiler?.frameworkExts ?? []), ...SCRIPT_EXT]))
📝 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 exts = Array.from(new Set(compiler?.frameworkExts.concat(SCRIPT_EXT)))
const exts = Array.from(new Set([...(compiler?.frameworkExts ?? []), ...SCRIPT_EXT]))
🤖 Prompt for AI Agents
In packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts around line
21, using compiler?.frameworkExts.concat(SCRIPT_EXT) can throw if compiler or
frameworkExts is undefined; change to concatenate against a safe default (e.g.
use (compiler?.frameworkExts ?? []) or an empty array fallback) so concat always
operates on an array and avoid build crash.

@codecov
Copy link
Copy Markdown

codecov Bot commented Sep 8, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 55.05%. Comparing base (9ac4b8b) to head (18f5916).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #18326   +/-   ##
=======================================
  Coverage   55.05%   55.05%           
=======================================
  Files         416      416           
  Lines       21560    21560           
  Branches     5285     5300   +15     
=======================================
  Hits        11870    11870           
- Misses       8034     8037    +3     
+ Partials     1656     1653    -3     
Flag Coverage Δ
taro-cli 72.85% <ø> (ø)
taro-runtime 59.87% <ø> (ø)
taro-web 53.13% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.
see 6 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 Sep 13, 2025
@ZakaryCode ZakaryCode merged commit 17f1844 into main Sep 19, 2025
39 checks passed
@ZakaryCode ZakaryCode deleted the fix/harmony-inject-env branch September 19, 2025 09:11
@github-project-automation github-project-automation Bot moved this to Done in 4.x Sep 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-harmony Target - 编译到 Harmony

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants