Skip to content
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

fix: ✅ ts annotated declare variable treat as top level variable #1682

Merged
merged 3 commits into from
Nov 13, 2024

Conversation

stormslowly
Copy link
Member

@stormslowly stormslowly commented Nov 7, 2024

close #1673

declare var foo: string;

console.log(foo); // <--  swc resolver treat it as a top level variable, due to the declare var

so we need to strip ts type first , then do the ctxt resolve

Summary by CodeRabbit

  • 新功能

    • 在配置文件中添加了新的键值对 "FOO": "\"bar\""
    • 新增全局变量 FOO,并添加测试用例以验证其值为 "bar"
    • 新增模块 clean_ctxt,用于清理语法上下文。
  • 文档

    • 引入了 path 模块以增强功能。
  • 重构

    • 优化了 TypeScript 和 TSX 文件的处理逻辑,增强了代码的可维护性。
    • 移除了不再需要的 CleanSyntaxContext 结构及其方法,简化了代码结构。

Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

Walkthrough

该拉取请求引入了对e2e/fixtures/config.define/expect.js文件的path模块的新导入声明,允许在文件中使用该模块的功能。此外,在e2e/fixtures/config.define/mako.config.json文件中添加了一个新的键值对"FOO": "\"bar\""。最后,在e2e/fixtures/config.define/src/index.tsx文件中声明了一个全局变量FOO,并新增了一个测试用例以验证FOO的值为"bar"

Changes

文件路径 更改摘要
e2e/fixtures/config.define/expect.js 新增导入声明:const path = require("path");
e2e/fixtures/config.define/mako.config.json 新增键值对:"FOO": "\"bar\""
e2e/fixtures/config.define/src/index.tsx 新增全局变量声明:declare var FOO: string;及测试用例
crates/mako/src/build/transform.rs 新增函数:strip_unresolved_tsstrip_unresolved_tsx
crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs 移除结构体CleanSyntaxContext及其方法
crates/mako/src/visitors.rs 新增模块:clean_ctxt
crates/mako/src/visitors/clean_ctxt.rs 新增结构体CleanSyntaxContext及其方法

Assessment against linked issues

Objective Addressed Explanation
页面显示 1 (#1673)

Possibly related PRs

Poem

在草地上跳跃,欢声笑语,
新增的路径,带来新趣。
FOO的秘密,藏在其中,
测试的乐章,轻声奏响。
代码的世界,日益精彩,
兔子欢舞,心中无忧! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
e2e/fixtures/config.define/src/index.tsx (2)

45-47: 建议优化测试用例描述

当前的测试描述 "should replace ts declare shallowed value" 不够具体。建议修改为更明确的描述,以便更好地理解测试目的。

建议修改如下:

-it("should replace ts declare shallowed value", ()=>{
+it("should correctly resolve TypeScript declared variable FOO with define value", ()=>{
   expect(FOO).toEqual("bar")
 });

3-3: 建议添加更多边界测试用例

当前的实现验证了基本功能,但建议添加以下场景的测试用例以确保完整性:

  1. 在不同作用域中使用声明变量
  2. 使用联合类型的声明变量
  3. 验证类型推导是否正确

这将帮助确保 SWC resolver 在各种场景下都能正确处理 TypeScript 声明。

Also applies to: 45-47

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eacee04 and b57d3b6.

📒 Files selected for processing (3)
  • e2e/fixtures/config.define/expect.js (1 hunks)
  • e2e/fixtures/config.define/mako.config.json (1 hunks)
  • e2e/fixtures/config.define/src/index.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • e2e/fixtures/config.define/expect.js
🔇 Additional comments (3)
e2e/fixtures/config.define/mako.config.json (2)

26-27: 配置格式正确且一致!

新添加的配置项 "FOO": "\"bar\"" 遵循了现有的字符串值转义规则,与其他配置项保持一致。


26-27: 验证配置是否正确应用

请确保此配置能够正确地被 SWC resolver 识别并替换 TypeScript 声明的变量。

运行以下脚本来验证相关配置的使用:

✅ Verification successful

配置已正确设置且被正确使用

通过验证发现:

  • e2e/fixtures/config.define/src/index.tsx 中正确声明了 FOO 变量并在测试中使用
  • 配置文件 mako.config.json 中的 "FOO": "\"bar\"" 值与测试预期的 "bar" 值相匹配
  • 变量声明、配置值和使用场景都保持一致,说明 SWC resolver 能够正确处理这个配置
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:验证 FOO 变量在项目中的声明和使用

# 测试:查找 FOO 变量的声明和使用位置
echo "查找 FOO 变量的声明:"
rg -t typescript "declare.*FOO"

echo "查找 FOO 变量的使用位置:"
rg "FOO" --type=typescript

Length of output: 208


Script:

#!/bin/bash
# 查找所有 TypeScript 和 JavaScript 文件中的 FOO 变量声明和使用
echo "查找 FOO 变量的声明和使用:"
rg "FOO" -g "*.{ts,js,tsx,jsx}"

# 查找配置文件中的 FOO 相关配置
echo -e "\n查找配置文件中的 FOO:"
rg "FOO" -g "*.{json,config.js}"

# 查找测试文件
echo -e "\n查找测试文件中的 FOO:"
fd "test|spec" -e ts -e js -e tsx -e jsx --exec rg "FOO" {}

Length of output: 522

e2e/fixtures/config.define/src/index.tsx (1)

3-3: 变量声明看起来没有问题!

声明符合 TypeScript 的最佳实践,类型注解恰当。

Copy link

codecov bot commented Nov 7, 2024

Codecov Report

Attention: Patch coverage is 60.71429% with 11 lines in your changes missing coverage. Please review.

Project coverage is 55.66%. Comparing base (eacee04) to head (31deba6).
Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
crates/mako/src/build/transform.rs 50.00% 11 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1682      +/-   ##
==========================================
+ Coverage   55.64%   55.66%   +0.02%     
==========================================
  Files         173      174       +1     
  Lines       17530    17545      +15     
==========================================
+ Hits         9754     9766      +12     
- Misses       7776     7779       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (4)
crates/mako/src/visitors/clean_ctxt.rs (2)

4-4: 建议为结构体添加文档注释

为了提高代码可维护性,建议添加文档注释来解释这个结构体的用途。

+/// 清理语法上下文的访问者实现
 struct CleanSyntaxContext;

6-8: 工厂函数实现正确,建议补充文档

函数实现符合 Rust 的惯用法,使用 as_folder 转换访问者为文件夹很恰当。建议添加文档说明其用途。

+/// 创建一个新的语法上下文清理器
+/// 
+/// 返回一个实现了 `VisitMut` 和 `Fold` trait 的访问者,
+/// 用于清理 TypeScript 声明变量的语法上下文。
 pub fn clean_syntax_context() -> impl VisitMut + Fold {
     as_folder(CleanSyntaxContext {})
 }
crates/mako/src/build/transform.rs (2)

80-94: 建议优化条件判断逻辑

在第80-94行的代码中,先判断了if is_tsx || is_ts,然后在内部又分别判断if is_tsxif is_ts。这种嵌套结构可能不够简洁。建议直接使用分支条件:

if is_tsx {
    // ...
} else if is_ts {
    // ...
}

这样可以减少嵌套层级,提高代码可读性。


33-33: 优化导入语句的组织方式

第33行的导入语句use crate::visitors::clean_ctxt::clean_syntax_context;位置稍显不统一。为保持代码的一致性和可读性,建议将其与其他visitors模块的导入语句放在一起,按照模块或功能进行分组。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b57d3b6 and 31deba6.

📒 Files selected for processing (4)
  • crates/mako/src/build/transform.rs (6 hunks)
  • crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs (2 hunks)
  • crates/mako/src/visitors.rs (1 hunks)
  • crates/mako/src/visitors/clean_ctxt.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/mako/src/visitors.rs
🔇 Additional comments (5)
crates/mako/src/visitors/clean_ctxt.rs (2)

1-2: 导入看起来完整且合适!

导入了必要的 SWC 核心组件用于语法上下文处理和访问者模式实现。


10-14: 实现逻辑正确且符合需求

VisitMut trait 的实现通过将语法上下文设置为空来实现类型擦除,这正确解决了 TypeScript 声明变量的处理问题。建议添加测试用例验证其行为。

crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs (2)

15-15: 导入声明优化完成!

导入声明的修改使代码结构更加清晰,通过移除未使用的导入并添加必要的clean_syntax_context导入,提高了代码的可维护性。

Also applies to: 18-18, 30-30


Line range hint 367-367: 建议验证语法上下文清理的时机是否合适

clean_syntax_context的调用位置在模块转换之后,这个时机看起来是合理的。但是建议验证以下几点:

  1. 在内部模块和根模块转换后的清理是否都是必要的
  2. 是否会影响后续的解析器(resolver)处理

Also applies to: 436-436

✅ Verification successful

Let me analyze the results and generate additional verification scripts to understand the impact of clean_syntax_context better.


语法上下文清理的时机是合适的

通过分析代码实现和使用情况,可以确认:

  1. clean_syntax_context 的实现非常简单,它只是将所有语法上下文重置为空
  2. 在模块转换后(内部模块和根模块)进行清理是必要的,因为:
    • 它确保了转换后的代码不会携带任何不必要的语法上下文
    • 这种清理不会影响后续的解析器处理,因为它只是重置上下文而不改变代码结构
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查是否存在其他地方也在使用clean_syntax_context
rg "clean_syntax_context" -A 3 -B 3

# 检查是否有相关的测试用例
fd -e rs -e tsx -e ts "test.*clean.*context" 

Length of output: 4261


Script:

#!/bin/bash
# Check the implementation of CleanSyntaxContext visitor
cat crates/mako/src/visitors/clean_ctxt.rs

# Check if there are any related resolver calls near clean_syntax_context
rg "resolver.*clean_syntax_context|clean_syntax_context.*resolver" -A 3 -B 3

# Look for any test files that might test module concatenation
fd -e rs "test.*module.*concat|test.*concat.*module"

Length of output: 554

crates/mako/src/build/transform.rs (1)

373-374: 确保tsx_strip函数的错误处理

在第373-374行,调用了ast.visit_mut_with(&mut tsx_strip(cm, context, top_level_mark, unresolved_mark));。请确保tsx_strip函数内部具有完善的错误处理机制,以防止在访问和修改AST时出现未捕获的异常,影响程序稳定性。

crates/mako/src/build/transform.rs Show resolved Hide resolved
@sorrycc
Copy link
Member

sorrycc commented Nov 8, 2024

why use test: prefix?

@stormslowly stormslowly changed the title test: ✅ ts annotated declare variable treat as top level variable fix: ✅ ts annotated declare variable treat as top level variable Nov 8, 2024
@stormslowly
Copy link
Member Author

!bench

@Wu-kung
Copy link
Contributor

Wu-kung commented Nov 8, 2024

📝 Benchmark detail: Open

Command Mean [s] Min [s] Max [s] Relative
./tmp/mako-eacee04c examples/with-antd --mode production 3.482 ± 0.043 3.440 3.570 1.01 ± 0.02
./tmp/mako-eacee04c examples/with-antd --mode production 3.457 ± 0.040 3.419 3.545 1.00

@xusd320 xusd320 merged commit dd22d96 into master Nov 13, 2024
21 checks passed
@xusd320 xusd320 deleted the fix/ts_declare_mako_unresolved_as_top_level branch November 13, 2024 08:46
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.

[Bug] EnvReplacer 在 Typescript Declare 环境下失效
4 participants