Skip to content

Conversation

Adamlyu-hub
Copy link
Contributor

@Adamlyu-hub Adamlyu-hub commented Aug 8, 2025

这个 PR 做了什么? (简要描述所做更改)
h5中编译器为vite时支持配置vite下所有server options,比如taro中配置devServer.allowedHosts。

这个 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

  • 新功能

    • H5 本地开发服务器新增可配置项:hmr、cors、watch、strictPort、middlewareMode、origin、allowedHosts 及文件系统访问控制(fs.strict、fs.allow、fs.deny),并支持可定制的 sourcemap 忽略规则。
  • 改进

    • 开发服务器解析与默认值更健壮,改进了 headers、proxy、hmr 兼容性与安全性;devServer 配置根据编译器类型支持 Vite 或 Webpack。

Copy link

coderabbitai bot commented Aug 8, 2025

Walkthrough

将 H5 的 Vite server 配置解析为 Vite 的 ServerOptions;用 hmr 替代 hot,并守卫解析与暴露 corswatchstrictPortmiddlewareModeoriginfsallowedHostsheadersproxysourcemapIgnoreList 等字段到返回的 server 配置中。

Changes

Cohort / File(s) Change Summary
Server 配置扩展
packages/taro-vite-runner/src/h5/config.ts
serverOption 视为 Vite ServerOptions;使用 hmr 替代 hot;新增并守卫解析 corswatchstrictPortmiddlewareModeoriginfsstrict/allow/deny)、allowedHostssourcemapIgnoreList(默认:忽略包含 node_modules 的源);保留并守卫 headers;将 proxy 明确为 `Record<string, string
类型定义更新
packages/taro/types/compile/config/h5.d.ts
引入 Vite 的 ServerOptions(别名 ViteServerOptions);将 IH5Config 中的 devServer 改为条件类型:T extends 'vite' ? ViteServerOptions : webpackDevServer.Configuration,并添加注释说明同时支持 Webpack 与 Vite。

Sequence Diagram(s)

sequenceDiagram
    rect rgb(245,250,255)
    participant Caller as 调用方
    participant ConfigFn as h5 config 解析
    participant Guards as 类型守卫/解析逻辑
    participant ServerCfg as 构建的 Vite server 配置
    end

    Caller->>ConfigFn: 传入 taroConfig.devServer / serverOption
    ConfigFn->>Guards: 断言为 Vite ServerOptions 并逐项守卫解析(hmr, cors, fs, allowedHosts, ...)
    Guards-->>ConfigFn: 返回解析值或默认值
    ConfigFn->>ServerCfg: 合并并构建最终 server 配置(包含 watch, fs, allowedHosts, sourcemapIgnoreList, origin, cors 等)
    ServerCfg-->>Caller: 返回完整的 Vite server 配置
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 分钟

Poem

🐇
我在配置草丛里轻敲,
把旧的 hot 换成了 hmr
cors 与 fs 手牵手,守卫稳稳绕,
sourcemap 默默避开 node_modules,
小兔一跃,配置更清朗。

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bba99b1 and cdc0d73.

📒 Files selected for processing (2)
  • packages/taro-vite-runner/src/h5/config.ts (3 hunks)
  • packages/taro/types/compile/config/h5.d.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/taro/types/compile/config/h5.d.ts
  • packages/taro-vite-runner/src/h5/config.ts
⏰ 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 - aarch64-apple-darwin
  • 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 - x86_64-pc-windows-msvc
  • GitHub Check: Build Rust WASM / stable - wasm32-wasi
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb41575 and d66bdb0.

📒 Files selected for processing (1)
  • packages/taro-vite-runner/src/h5/config.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ianzone
PR: NervJS/taro#18146
File: packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/package.json:12-14
Timestamp: 2025-08-08T02:32:58.207Z
Learning: 在 Taro 项目的 pnpm 工作区中,Vitest 相关依赖(vitest 和 vitest/coverage-istanbul)被管理在根目录的 package.json 中,而不是各个子包的 devDependencies 中。这是 monorepo 中依赖提升的标准做法。
Learnt from: ianzone
PR: NervJS/taro#17746
File: packages/taro-runtime/tsdown.config.ts:10-16
Timestamp: 2025-05-25T18:02:31.387Z
Learning: 在 taro-runtime 包的 tsdown 配置中,必须禁用 treeshake 来保留 dom-external/index.js 文件。
📚 Learning: 2025-05-25T18:02:31.387Z
Learnt from: ianzone
PR: NervJS/taro#17746
File: packages/taro-runtime/tsdown.config.ts:10-16
Timestamp: 2025-05-25T18:02:31.387Z
Learning: 在 taro-runtime 包的 tsdown 配置中,必须禁用 treeshake 来保留 dom-external/index.js 文件。

Applied to files:

  • packages/taro-vite-runner/src/h5/config.ts
🔇 Additional comments (1)
packages/taro-vite-runner/src/h5/config.ts (1)

188-189: 确认:sourcemapIgnoreList 在 Vite server 下为有效配置

Vite 官方文档已明确支持在开发服务器阶段使用 server.sourcemapIgnoreList,当前将其放在 server 作用域是正确的。若需在生产构建阶段同样忽略特定路径,可以在 build.rollupOptions.output.sourcemapIgnoreList 中添加等效配置。

无需删除或移动此行(packages/taro-vite-runner/src/h5/config.ts:188-189):

-        sourcemapIgnoreList: serverOption.sourcemapIgnoreList ?? ((sourcePath) => sourcePath.includes('node_modules')),

Likely an incorrect or invalid review comment.

Comment on lines 190 to 191
cors: serverOption.cors ?? true,
warmup: serverOption.warmup ?? {},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

规范 origin/cors/warmup 的类型与默认值,避免传入非法类型

  • origin 需为字符串;建议仅在为字符串时透传。
  • cors 支持 boolean 或对象;建议仅在为 boolean 或对象时透传,否则使用默认 true。
  • warmup 在 Vite 5 中为对象配置;若用户传入 true/false,当前 “?? {}” 会把 boolean 直接透传,存在类型风险。

请应用如下变更:

-        origin: serverOption.origin,
-        cors: serverOption.cors ?? true,
-        warmup: serverOption.warmup ?? {},
+        origin: isString(serverOption.origin) ? serverOption.origin : undefined,
+        cors: (isBoolean(serverOption.cors) || isObject(serverOption.cors)) ? serverOption.cors : true,
+        warmup: isObject(serverOption.warmup) ? serverOption.warmup : undefined,
📝 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
cors: serverOption.cors ?? true,
warmup: serverOption.warmup ?? {},
origin: isString(serverOption.origin) ? serverOption.origin : undefined,
cors: (isBoolean(serverOption.cors) || isObject(serverOption.cors)) ? serverOption.cors : true,
warmup: isObject(serverOption.warmup) ? serverOption.warmup : undefined,
🤖 Prompt for AI Agents
In packages/taro-vite-runner/src/h5/config.ts around lines 190 to 191, the
properties origin, cors, and warmup need stricter type validation and default
handling to avoid passing invalid types. Update the code to only pass origin if
it is a string; for cors, only pass it if it is a boolean or an object,
otherwise default to true; for warmup, ensure it is an object and do not pass
boolean values directly, defaulting to an empty object if invalid. Implement
these type checks and conditional assignments accordingly.

@Single-Dancer Single-Dancer added this to the 4.1.6 milestone Aug 8, 2025
This was referenced Aug 9, 2025
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: 0

♻️ Duplicate comments (3)
packages/taro-vite-runner/src/h5/config.ts (3)

113-117: 仅当 watch 为对象时透传,避免默认 {} 覆盖 Vite 默认与潜在类型不匹配

  • 当前实现即使用户未配置或传入 boolean,也会始终传 {},与期望的 “未设置 => 让 Vite 采用默认值” 不一致。
  • 建议:仅在为对象时设置;否则不传该键(undefined)。
-  let watch: Record<string, any> = {} // 默认值为空对象
-  const watchOption = (serverOption as any).watch
-  if (isObject<Record<string, any>>(watchOption)) {
-    watch = watchOption
-  }
+  let watch: Record<string, any> | undefined
+  const watchOption = (serverOption as any).watch
+  if (isObject<Record<string, any>>(watchOption)) {
+    watch = watchOption
+  }

@@
-        watch,
+        watch,

Also applies to: 237-237


140-144: 仅当 origin 为字符串时透传;避免以空字符串覆盖默认行为

  • 当前默认将 origin 设为 '' 并始终传入,可能改变 Vite 默认值。
  • 建议:未配置时不传;为字符串时再透传。
-  let origin = '' // 默认值为空字符串
+  let origin: string | undefined
   const originOption = (serverOption as any).origin
   if (isString(originOption)) {
     origin = originOption
   }
@@
-        origin,
+        origin,

Also applies to: 247-247


145-159: 修正 fs. 的来源:应从 serverOption.fs 读取,否则会忽略用户配置*

  • 目前从 serverOption.strict/allow/deny 顶层读取,违背 Vite 配置结构(应来自 serverOption.fs?.*),导致用户传入的 devServer.fs 被忽略。
  • 建议改为从 serverOption.fs 读取,并为每个字段做类型守卫与默认值回退。
-  let fsStrict = true // 默认值为true(自Vite 2.7起默认启用)
-  const fsStrictOption = (serverOption as any).strict
-  if (isBoolean(fsStrictOption)) {
-    fsStrict = fsStrictOption
-  }
-  let fsAllow: string[] = [] // 默认值为空数组
-  const fsAllowOption = (serverOption as any).allow
-  if (Array.isArray(fsAllowOption)) {
-    fsAllow = fsAllowOption
-  }
-  let fsDeny: string[] = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'] // 默认值为安全的黑名单
-  const fsDenyOption = (serverOption as any).deny
-  if (Array.isArray(fsDenyOption)) {
-    fsDeny = fsDenyOption
-  }
+  // fs 选项应从 serverOption.fs 读取
+  const fsOption = (serverOption as any).fs
+  let fsStrict = true
+  let fsAllow: string[] = []
+  let fsDeny: string[] = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**']
+  if (isObject<Record<string, any>>(fsOption)) {
+    if (isBoolean(fsOption.strict)) fsStrict = fsOption.strict
+    if (Array.isArray(fsOption.allow)) fsAllow = fsOption.allow
+    if (Array.isArray(fsOption.deny)) fsDeny = fsOption.deny
+  }
@@
-        fs: {
-          strict: fsStrict,
-          allow: fsAllow,
-          deny: fsDeny,
-        },
+        fs: {
+          strict: fsStrict,
+          allow: fsAllow,
+          deny: fsDeny,
+        },

Also applies to: 238-242

🧹 Nitpick comments (1)
packages/taro-vite-runner/src/h5/config.ts (1)

229-249: 建议补充集成用例覆盖新透传的 server 选项

  • 为避免回归,建议在 E2E/集成测试中校验以下字段是否按用户配置透传到 Vite:corswatchstrictPortmiddlewareModeoriginfs.*allowedHosts(以及若确认支持则覆盖 server.base)。

我可以基于当前测试框架草拟一组用例(含不同类型输入与未配置时的默认行为),需要的话告知我要覆盖的最小浏览器环境与 Vite 版本矩阵。

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7719ef5 and ad1a40a.

📒 Files selected for processing (1)
  • packages/taro-vite-runner/src/h5/config.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/taro-vite-runner/src/h5/config.ts (3)
packages/shared/src/is.ts (2)
  • isBoolean (17-19)
  • isObject (13-15)
packages/taro-vite-runner/src/utils/index.ts (1)
  • getMode (108-114)
packages/taro-helper/src/constants.ts (1)
  • defaultMainFields (240-240)
⏰ 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). (6)
  • GitHub Check: Build Rust Binding / stable - x86_64-unknown-linux-musl
  • GitHub Check: Build Rust Binding / stable - aarch64-apple-darwin
  • GitHub Check: Build Rust Binding / stable - x86_64-unknown-linux-gnu
  • 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 WASM / stable - wasm32-wasi
🔇 Additional comments (4)
packages/taro-vite-runner/src/h5/config.ts (4)

108-112: cors 类型守卫与默认值处理合理

  • 仅在为 boolean 或对象时透传,并默认 true,符合 Vite 行为预期。

118-122: strictPort / middlewareMode 透传方式正确

  • strictPort 仅在 boolean 时透传,默认 false。
  • middlewareMode 仅允许 'ssr' 或 'html',否则禁用,符合 Vite 类型定义的常见用法。

Also applies to: 123-127


165-170: 请确认 taro-vite-runner 依赖的 Vite 版本是否 ≥ v4.5.6

  • server.allowedHosts 配置项于 Vite v6.0.9(2025-01-20)首次引入,并已回填至 v5.4.12 与 v4.5.6 补丁版本;类型定义为 string[] | true,默认值 [],设为 true 表示允许所有主机(不推荐)。
  • 当前实现逻辑已正确支持 true | string[] | string(字符串时封装为单元素数组),未配置时保持 undefined,符合预期。

128-139: 不需要移除 server.base 配置

server.base 确实是 Vite Server Options 中的有效选项,类型定义为 string | undefined,用于为开发服务器的 HTTP 请求添加子路径前缀,并且必须以 / 开头和结尾。详见官方文档:

  • “### server.base” 条目明确说明了该配置项的存在和用途。 (v2.vite.dev)

因此,原评论中“建议移除对 server.base 的设置”基于对配置项是否存在的误解,可忽略该建议。

Likely an incorrect or invalid review comment.

Copy link

codecov bot commented Aug 21, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 55.06%. Comparing base (1d2aead) to head (cdc0d73).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##             main   #18152    +/-   ##
========================================
  Coverage   55.06%   55.06%            
========================================
  Files         416      416            
  Lines       21563    21563            
  Branches     5286     5283     -3     
========================================
  Hits        11873    11873            
+ Misses       8161     8039   -122     
- Partials     1529     1651   +122     
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 41 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.

@coderabbitai coderabbitai bot requested a review from tutuxxx August 21, 2025 08:21
@Single-Dancer Single-Dancer merged commit d1f3db8 into NervJS:main Aug 28, 2025
34 of 35 checks passed
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.

2 participants