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: replace the "typeof __webpack_require__" content #1688

Merged
merged 6 commits into from
Dec 17, 2024

Conversation

notcold
Copy link
Contributor

@notcold notcold commented Nov 11, 2024

close #1291

export function getNodeRequire() {
  return typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require;
}

webpack_require is a special variable in the webpack so it should be removed

Summary by CodeRabbit

  • 新特性

    • 引入了 WebpackRuntimeReplacement 访问者,增强了模块转换功能。
    • 新增模块 webpack_runtime_replacement,扩展了功能。
    • 添加了处理 Webpack 相关标识符的功能,支持特定的代码转换。
  • 测试

    • 包含三个单元测试,验证 Webpack 标识符的转换行为。

Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

概述

遍历

此更改引入了一个新的访问者 WebpackRuntimeReplacement,用于处理 Webpack 运行时特定标识符。新访问者被添加到转换过程中,专门处理 typeof 运算符下的 Webpack 特殊标识符,将其替换为 undefined。这一变更旨在解决 Webpack 特殊语法在代码转换过程中的兼容性问题。

变更

文件 变更摘要
crates/mako/src/build/transform.rs transform 方法中添加 WebpackRuntimeReplacement 访问者
crates/mako/src/visitors.rs 添加 webpack_runtime_replacement 模块
crates/mako/src/visitors/webpack_runtime_replacement.rs 新增文件,实现 Webpack 运行时替换逻辑

对链接问题的评估

目标 已解决 说明
处理 typeof __webpack_require__ 场景
将特殊 Webpack 标识符转换为 undefined

诗歌

兔子编码,魔法飞舞,
Webpack 的谜题,悄然化解。
标识符跳跃,转换如风,
代码之路,畅通无阻。
🐰✨ 编程的艺术,在此绽放!


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@notcold notcold closed this Nov 11, 2024
@notcold notcold reopened this Nov 11, 2024
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 (4)
crates/mako/src/visitors/webpack_require.rs (4)

5-20: 建议对常量进行分组以提高可维护性

建议将相关的 webpack 常量按功能进行分组,例如:

  • 核心常量(如 WEBPACK_REQUIREWEBPACK_MODULES
  • 运行时常量(如 WEBPACK_HASHWEBPACK_RUNTIME_ID
  • 共享作用域常量(如 WEBPACK_SHARE_SCOPESWEBPACK_INIT_SHARING

这样可以提高代码的可读性和维护性。


22-53: 建议添加文档注释

为了提高代码的可维护性和可读性,建议为以下项添加文档注释:

  • WebpackRequire 结构体的用途和职责
  • new 方法的参数说明
  • is_ident_webpack 方法的功能说明、参数和返回值解释

示例文档注释:

/// 处理 webpack 相关标识符的 AST 访问器
pub struct WebpackRequire {
    /// 未解析标记,用于上下文匹配
    pub unresolved_mark: Mark,
}

55-65: 建议完善注释说明转换逻辑

当前的注释只说明了要查找 "typeof webpack_require",建议补充:

  1. 为什么要进行这种转换
  2. 转换的具体规则
  3. 转换后的预期效果

建议添加如下注释:

/// 访问并转换 AST 中的一元表达式
/// 
/// 将 `typeof __webpack_require__` 等形式的表达式转换为 `typeof void 0`,
/// 以避免 webpack 特殊语法导致的问题。
fn visit_mut_unary_expr(&mut self, unary_expr: &mut UnaryExpr) {

67-99: 建议增加更多测试用例

当前的测试覆盖了基本场景,建议添加以下测试用例:

  1. 测试所有 webpack 相关标识符的转换
  2. 测试非 webpack 标识符不被转换的情况
  3. 测试嵌套表达式中的转换
  4. 测试错误处理场景

示例测试用例:

#[test]
fn test_nested_typeof() {
    assert_eq!(
        run(r#"foo(typeof __webpack_require__, typeof __webpack_modules__);"#),
        r#"foo(typeof void 0, typeof void 0);"#
    );
}

#[test]
fn test_non_webpack_ident() {
    let code = r#"typeof normal_require === 'function';"#;
    assert_eq!(run(code), code);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b6f4f5e and 9e57431.

📒 Files selected for processing (1)
  • crates/mako/src/visitors/webpack_require.rs (1 hunks)
🔇 Additional comments (1)
crates/mako/src/visitors/webpack_require.rs (1)

1-99: 代码实现符合需求,建议合并

整体实现完整且符合 PR 目标,成功解决了 webpack 特殊语法的处理问题。建议在完成上述优化后合并此 PR。

Copy link

codecov bot commented Nov 13, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 54.92%. Comparing base (68e946c) to head (a04d59c).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1688      +/-   ##
==========================================
+ Coverage   54.89%   54.92%   +0.02%     
==========================================
  Files         178      180       +2     
  Lines       17871    17930      +59     
==========================================
+ Hits         9811     9848      +37     
- Misses       8060     8082      +22     

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

@Jinbao1001 Jinbao1001 requested a review from sorrycc December 4, 2024 07:48
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 (1)
crates/mako/src/visitors/webpack_require.rs (1)

37-47: 建议增强错误处理

当前实现在处理 AST 转换时没有考虑可能的错误情况。建议添加错误处理逻辑,并在遇到意外情况时提供有意义的错误信息。

例如,可以考虑:

  1. 在转换失败时记录详细的错误信息
  2. 添加对无效 AST 结构的防御性检查
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9e57431 and 02e9ce5.

📒 Files selected for processing (1)
  • crates/mako/src/visitors/webpack_require.rs (1 hunks)
🔇 Additional comments (3)
crates/mako/src/visitors/webpack_require.rs (3)

5-20: 建议优化常量数组的实现方式

参考现有代码库中的实现模式(例如 crates/mako/src/build/load.rs),建议将 WEBPACK_VALUES 改为 const slice 的形式,这样可以提高代码的一致性和可维护性。

-pub const WEBPACK_VALUES: [&str; 14] = [
+pub const WEBPACK_VALUES: &[&str] = &[
     "__webpack_get_script_filename__",
     // ... other values ...
     "__webpack_base_uri__",
-];
+];

50-89: 测试实现完善,覆盖了关键场景

测试用例设计合理,包括:

  1. 基本的 typeof __webpack_require__ 转换
  2. __webpack_modules__ 的处理
  3. 嵌套 typeof 的边缘情况

测试辅助函数 run 的实现也很规范,正确处理了测试环境的设置。


1-89: 整体实现符合需求,建议进行小幅优化

代码整体实现符合 PR 的目标,成功处理了 webpack require 相关的表达式转换。建议在合并前:

  1. 移除调试打印语句
  2. 优化常量数组的实现
  3. 加强错误处理机制

这些改进将使代码更加健壮和可维护。

crates/mako/src/visitors/webpack_require.rs Outdated Show resolved Hide resolved
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 (4)
crates/mako/src/visitors/webpack_require.rs (4)

5-20: 建议为常量添加文档注释

WEBPACK_VALUES 常量的实现看起来很完整,包含了所有需要处理的 webpack 标识符。建议添加文档注释来说明每个标识符的用途,这样可以帮助其他开发者更好地理解和维护代码。

建议添加如下文档注释:

+/// Webpack 运行时使用的特殊标识符列表
+/// 这些标识符在编译时会被转换为 `undefined`
pub const WEBPACK_VALUES: [&str; 14] = [

22-33: 建议增强错误处理和文档

结构体和方法的实现逻辑清晰,但建议添加以下改进:

  1. 为结构体和公共方法添加文档注释
  2. 考虑为 is_ident_webpack 添加单元测试

建议添加如下文档:

+/// 处理 Webpack 相关标识符的 AST 访问器
+/// 
+/// 主要用于将 `typeof __webpack_require__` 等表达式转换为 `typeof undefined`
pub struct WebpackRequire {
    pub unresolved_mark: Mark,
}

impl WebpackRequire {
+    /// 创建新的访问器实例
+    /// 
+    /// # Arguments
+    /// * `unresolved_mark` - 用于标识未解析标识符的标记
    pub fn new(unresolved_mark: Mark) -> Self {

35-47: 实现逻辑正确,建议优化模式匹配

访问器的实现逻辑正确,能够有效处理 typeof 表达式。不过可以考虑使用更简洁的模式匹配语法。

建议重构为:

 impl VisitMut for WebpackRequire {
     fn visit_mut_unary_expr(&mut self, unary_expr: &mut UnaryExpr) {
-        if unary_expr.op.as_str() == "typeof"
-            && let Some(arg_ident) = unary_expr.arg.as_ident()
-            && self.is_ident_webpack(arg_ident, &self.unresolved_mark)
-        {
+        match (unary_expr.op.as_str(), unary_expr.arg.as_ident()) {
+            ("typeof", Some(arg_ident)) if self.is_ident_webpack(arg_ident, &self.unresolved_mark) => {
                 unary_expr.arg = Expr::undefined(DUMMY_SP)
-        } else {
-            unary_expr.visit_mut_children_with(self);
+            }
+            _ => unary_expr.visit_mut_children_with(self)
         }
     }
 }

49-88: 建议增加更多测试用例

当前的测试覆盖了基本场景,但建议添加以下测试场景以提高代码的健壮性:

  1. 处理多个嵌套的 typeof 表达式
  2. 处理不在 WEBPACK_VALUES 列表中的标识符
  3. 处理复杂表达式中的 webpack 标识符

建议添加如下测试用例:

#[test]
fn test_multiple_typeof() {
    assert_eq!(
        run(r#"typeof typeof typeof __webpack_modules__;"#),
        r#"typeof typeof typeof void 0;"#
    );
}

#[test]
fn test_non_webpack_ident() {
    let input = r#"typeof normalFunction;"#;
    assert_eq!(run(input), input);
}

#[test]
fn test_complex_expression() {
    assert_eq!(
        run(r#"typeof __webpack_require__ && typeof __webpack_modules__;"#),
        r#"typeof void 0 && typeof void 0;"#
    );
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 02e9ce5 and 601d5b2.

📒 Files selected for processing (1)
  • crates/mako/src/visitors/webpack_require.rs (1 hunks)

@notcold
Copy link
Contributor Author

notcold commented Dec 13, 2024

@stormslowly codecov/project 掉了怎么办好像跟pr没有关系?

Copy link
Member

@sorrycc sorrycc left a comment

Choose a reason for hiding this comment

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

webpack_require > webpack_runtime_replacement 吧,看内容,已经做的不止是 webpack_require 替换这件事了。

@notcold
Copy link
Contributor Author

notcold commented Dec 16, 2024

@sorrycc rename了,调整了对应引用

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

🧹 Nitpick comments (2)
crates/mako/src/visitors/webpack_runtime_replacement.rs (2)

30-32: 建议优化参数使用

在方法is_ident_webpack中,参数unresolved_mark已经是self的成员变量,无需作为参数传入。可以直接使用self.unresolved_mark来简化代码。

建议修改如下:

-fn is_ident_webpack(&self, ident: &Ident, unresolved_mark: &Mark) -> bool {
-    WEBPACK_VALUES.iter().any(|&i| i == &ident.sym) && ident.ctxt.outer() == *unresolved_mark
+fn is_ident_webpack(&self, ident: &Ident) -> bool {
+    WEBPACK_VALUES.iter().any(|&i| i == &ident.sym) && ident.ctxt.outer() == self.unresolved_mark
 }

并在调用该方法时,省略多余的参数:

 if unary_expr.op.as_str() == "typeof"
     && let Some(arg_ident) = unary_expr.arg.as_ident()
-    && self.is_ident_webpack(arg_ident, &self.unresolved_mark)
+    && self.is_ident_webpack(arg_ident)
 {
     unary_expr.arg = Expr::undefined(DUMMY_SP)
 }

57-75: 建议增加单元测试覆盖更多Webpack标识符

当前的单元测试仅针对部分WEBPACK_VALUES中的标识符,建议增加测试用例,覆盖所有的Webpack标识符,确保替换逻辑的完整性和可靠性。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1efd7be and a04d59c.

📒 Files selected for processing (3)
  • crates/mako/src/build/transform.rs (2 hunks)
  • crates/mako/src/visitors.rs (1 hunks)
  • crates/mako/src/visitors/webpack_runtime_replacement.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/mako/src/visitors.rs
  • crates/mako/src/build/transform.rs
🔇 Additional comments (1)
crates/mako/src/visitors/webpack_runtime_replacement.rs (1)

38-41: 确认Rust版本兼容性

if条件中使用let绑定的语法(如if let Some(...) = ... && ...)需要Rust 1.65或以上版本的支持。请确认项目的最低Rust版本要求符合此语法需求。

您可以运行以下脚本以检查项目的Rust版本配置:

✅ Verification successful

项目使用 nightly-2024-07-21 版本,支持该语法特性

项目的 rust-toolchain.toml 文件明确指定使用 nightly-2024-07-21 版本。在 if let 条件中使用 && 的语法(RFC-2947)已在 Rust 1.65(2022年11月发布)中稳定,而项目使用的 nightly-2024-07-21 版本远新于此要求,因此完全支持该语法特性。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查项目的Rust最低支持版本

# 查看rust-toolchain文件中的版本
if [ -f rust-toolchain ]; then
    echo "rust-toolchain文件中指定的Rust版本为:"
    cat rust-toolchain
else
    echo "未找到rust-toolchain文件,检查Cargo.toml中的rust版本。"
    rg '^rust-version' Cargo.toml
fi

Length of output: 296


Script:

#!/bin/bash
# 检查所有Cargo.toml文件中的rust-version和MSRV相关配置
fd Cargo.toml --exec rg -l 'rust-version|MSRV'

# 检查.github/workflows目录下的CI配置文件中的Rust版本
fd -e yml -e yaml . .github/workflows/ --exec rg -l 'rust|MSRV'

# 检查项目根目录下的README或其他文档中的Rust版本要求
fd -e md . --exec rg -l 'rust-version|MSRV|Rust version'

Length of output: 266


Script:

#!/bin/bash
# 检查CI配置文件中的Rust版本设置
echo "=== CI工作流中的Rust版本配置 ==="
rg -A 5 'rust-toolchain|rust-version|rustup' .github/workflows/ci.yml
rg -A 5 'rust-toolchain|rust-version|rustup' .github/workflows/node-bind-build.yml
rg -A 5 'rust-toolchain|rust-version|rustup' .github/workflows/codecov.yml

# 检查项目中是否有rust-toolchain.toml文件
echo -e "\n=== 查找rust-toolchain.toml ==="
fd rust-toolchain.toml

Length of output: 3412


Script:

#!/bin/bash
# 检查rust-toolchain.toml的具体内容
echo "=== rust-toolchain.toml的内容 ==="
cat rust-toolchain.toml

# 检查.github/actions/rustup中的配置
echo -e "\n=== .github/actions/rustup/action.yml的内容 ==="
cat .github/actions/rustup/action.yml

Length of output: 2273

@sorrycc sorrycc closed this Dec 17, 2024
@sorrycc sorrycc reopened this Dec 17, 2024
@sorrycc sorrycc merged commit 31b0d45 into umijs:master Dec 17, 2024
20 of 21 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.

RFC:webpack 特殊语法排除 typeof 的场景
3 participants