-
Notifications
You must be signed in to change notification settings - Fork 4.9k
feat(harmony): 修复鸿蒙 assets 文件后缀 & 修复样式 filter 规则 #18376
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
Conversation
Walkthrough此次变更包含三处:1) 将 Harmony 注入环境的 Vite 插件导出由接收 platform 参数改为使用 this 绑定;2) Harmony 资源命名与磁盘路径策略调整,扩展名仅入磁盘路径不入公开 URL;3) 页面编译过滤范围扩展为 sourceDir 下的所有文件。 Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Dev as Vite (build/serve)
participant P as inject-env 插件
participant H as Harmony 实例(this)
Dev->>+P: 初始化/调用插件钩子
P->>+H: this.getConfig()
H-->>-P: 返回配置(含 businessId)
P->>H: 访问 this.context.runnerUtils
P-->>-Dev: 返回注入后的处理结果
note over P,H: 插件从参数读取 改为从 this 读取
sequenceDiagram
autonumber
participant U as 调用方
participant A as asset.ts
U->>+A: 请求生成资源引用(相对路径)
A->>A: 提取扩展名 ext
A->>A: 规范化名称(去扩展名)
A->>A: 生成磁盘路径: base/media/<规范名><ext>
A->>A: 生成公开URL: resource://base/media/<规范名>
A-->>-U: {resourcePath 含扩展名, URL 不含扩展名}
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information. Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).Please share your feedback with us on this Discord post. 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. Comment |
There was a problem hiding this 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/taro-vite-runner/src/harmony/asset.ts (2)
286-288: 二进制资源被按 UTF‑8 写入,会损坏图片/音频等文件此处 content 为 Buffer,但强制指定
{ encoding: 'utf-8' }会破坏二进制内容。请移除编码参数:
- fs.writeFileSync(resourcePath, content, { - encoding: 'utf-8', - }) + fs.writeFileSync(resourcePath, content)
290-292: 缓存值与返回值不一致,导致重复加载时导出文件系统路径而非 resource:// URL
cache.set(id, resourcePath)会让下次命中缓存返回磁盘路径,随后load导出成为绝对文件路径,破坏运行时预期。修正为缓存并返回统一的 resource:// URL:
- cache.set(id, resourcePath) - return 'resource://base/media/' + resourceName + const publicUrl = 'resource://base/media/' + resourceName + cache.set(id, publicUrl) + return publicUrlpackages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts (1)
21-23: 潜在空引用崩溃:compiler 可能为空时.concat调用会抛错
compiler?.frameworkExts.concat(...)中compiler?.frameworkExts可能为undefined,随后对concat的调用将抛异常。建议健壮化合并逻辑:
- const exts = Array.from(new Set(compiler?.frameworkExts.concat(SCRIPT_EXT))) + const exts = Array.from(new Set([...(compiler?.frameworkExts ?? []), ...SCRIPT_EXT]))
🧹 Nitpick comments (5)
packages/taro-vite-runner/src/harmony/page.ts (1)
25-25: Windows 路径匹配风险:对 include 模式中的 sourceDir 做路径归一化在 Windows 下,直接拼接
${sourceDir}/**可能因反斜杠导致 picomatch 匹配失败。建议利用已引入的 escapePath 归一化后再拼接。应用如下补丁:
- const filter = createFilterWithCompileOptions(taroConfig.compile, [`${sourceDir}/**`, /(?<=node_modules[\\/]).*taro/], []) + const filter = createFilterWithCompileOptions( + taroConfig.compile, + [`${escapePath(sourceDir)}/**`, /(?<=node_modules[\\/]).*taro/], + [] + )packages/taro-vite-runner/src/harmony/asset.ts (2)
282-285: 资源名规范化存在两个小问题:字符类范围与移除扩展名方式
- 使用
[^A-z0-9]会把[\]^_\`` 等非法字符也当作“字母”,建议改为[^A-Za-z0-9_]`。- 通过
.replace(ext, '')可能误删路径中间与扩展名同名的片段,建议仅删除末尾扩展名。应用更稳妥的生成方式:
- const ext = path.extname(file) - const resourceName = path.relative(appRoot, file).replace(ext, '').replace(/^[\\/]+/, '').replace(/[^A-z0-9]+/g, '_') + const ext = path.extname(file) + const rel = path.relative(appRoot, file).replace(/^[\\/]+/, '') + const base = ext ? rel.slice(0, -ext.length) : rel + const resourceName = base.replace(/[^A-Za-z0-9_]+/g, '_')
282-292: 可选:避免同名冲突(不同子目录/不同扩展名)导致覆盖扁平化并去除扩展名会增加重名概率。可在冲突时追加短哈希后缀。
示例补丁(仅在发生冲突时追加 8 位 hash):
- const resourcePath = path.join(escapePath(outputRoot), '..', 'resources/base/media', `${resourceName}${ext}`) + const mediaDir = path.join(escapePath(outputRoot), '..', 'resources/base/media') + let finalName = resourceName + let resourcePath = path.join(mediaDir, `${finalName}${ext}`) + if (fs.existsSync(resourcePath)) { + finalName = `${resourceName}_${getHash(rel).slice(0, 8)}` + resourcePath = path.join(mediaDir, `${finalName}${ext}`) + } ... - const publicUrl = 'resource://base/media/' + resourceName + const publicUrl = 'resource://base/media/' + finalNamepackages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts (2)
70-77: 使用 Vite 插件上下文的 warn 接口,而非 console.warn在插件中调用
console.warn无法纳入构建日志体系。应使用pluginContext.warn(...)。应用如下补丁:
- console.warn(`Error: 使用定位相关 API(${path.node.callee.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`) + pluginContext.warn(`使用定位相关 API(${path.node.callee.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId。`) ... - console.warn(`Error: 使用定位相关 API(${path.node.property.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId.`) + pluginContext.warn(`使用定位相关 API(${path.node.property.name}) 时,需要配置 defineConstants.LOCATION_APIKEY 为 businessId。`)Also applies to: 95-101
47-56: 命名遮蔽可读性较差:局部变量 imported 与外层 imported 同名
const { imported } = spec会遮蔽上层的imported布尔变量,读者易混淆。小改名即可:
- const { imported } = spec - const propertyName = t.isIdentifier(imported) ? imported.name : imported.value + const { imported: importedToken } = spec + const propertyName = t.isIdentifier(importedToken) ? importedToken.name : importedToken.value
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts(1 hunks)packages/taro-vite-runner/src/harmony/asset.ts(1 hunks)packages/taro-vite-runner/src/harmony/page.ts(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: ianzone
PR: NervJS/taro#18150
File: packages/taro-platform-harmony-hybrid/package.json:43-45
Timestamp: 2025-09-05T18:40:45.775Z
Learning: 在 tarojs/plugin-platform-harmony-hybrid 包中,tarojs/components-library-react、tarojs/components-library-solid 和 tarojs/components-library-vue3 必须作为直接依赖(dependencies)而不能作为 peer 依赖,因为插件源码中有对这些包的直接引用,包括 componentAdapter* getter 方法和 webpack 别名配置。
🧬 Code graph analysis (2)
packages/taro-vite-runner/src/harmony/asset.ts (2)
packages/taro-vite-runner/src/utils/index.ts (1)
escapePath(215-217)packages/taro-platform-harmony-cpp/scripts/constant.ts (1)
outputRoot(15-15)
packages/taro-vite-runner/src/harmony/page.ts (1)
packages/taro-vite-runner/src/utils/createFilter.ts (1)
createFilterWithCompileOptions(79-99)
⏰ 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). (5)
- GitHub Check: Build Rust Binding / stable - x86_64-pc-windows-msvc
- GitHub Check: Build Rust Binding / stable - x86_64-apple-darwin
- GitHub Check: Build Rust Binding / stable - x86_64-unknown-linux-gnu
- GitHub Check: Build Rust Binding / stable - aarch64-apple-darwin
- GitHub Check: Build Rust WASM / stable - wasm32-wasi
🔇 Additional comments (2)
packages/taro-platform-harmony-cpp/src/program/vite/inject-env.ts (1)
8-13: 确认:inject-env 的 this 绑定已正确使用(无需修改)packages/taro-platform-harmony-cpp/src/program/index.ts 的 modifyPageConfig 中通过 injectEnv.call(this, opt) 调用(第116–119行),已为导出函数的 this 参数提供正确绑定。
packages/taro-vite-runner/src/harmony/asset.ts (1)
284-285: 确认 outputRoot 是否为 HAP 输出根 — 相对回退 '..' 可能出错仓库检索仅在 packages/taro-vite-runner/src/harmony/asset.ts:284 发现该写法(
const resourcePath = path.join(escapePath(outputRoot), '..', 'resources/base/media', ...));若 outputRoot 已经是 HAP 的输出根,向上退一层会把资源写到错误位置。建议核验 outputRoot 的来源/定义(配置或 constant),并改为基于 Harmony 打包根计算资源目录或显式构建目标路径(不要依赖通用的 '..' 回退),或在代码中对 outputRoot 的预期结构加断言/注释以避免误写。
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #18376 +/- ##
=======================================
Coverage 55.05% 55.05%
=======================================
Files 416 416
Lines 21560 21560
Branches 5284 5284
=======================================
Hits 11870 11870
+ Misses 8167 8077 -90
- Partials 1523 1613 +90
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
这个 PR 做了什么? (简要描述所做更改)
这个 PR 是什么类型? (至少选择一个)
这个 PR 涉及以下平台:
Summary by CodeRabbit