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: umd should be import as cjs #1642

Merged
merged 3 commits into from
Oct 23, 2024
Merged

fix: umd should be import as cjs #1642

merged 3 commits into from
Oct 23, 2024

Conversation

Jinbao1001
Copy link
Member

@Jinbao1001 Jinbao1001 commented Oct 15, 2024

import xxx from 'xxx' // umd module

before:

if (typeof define === 'function' && define.amd) {
        define(xxx);
    } 

after:

if (typeof void 0 === 'function' && define.amd) {
        define(xxx);
    } 

Summary by CodeRabbit

  • 新功能

    • 添加了对 AMD 和 CommonJS 兼容模块的支持。
    • 引入新的 amd_define_overrides 功能,用于转换特定的 AST 表达式。
    • 新增测试用例以增强模块导出功能的覆盖率。
  • 文档

    • 创建了新的配置文件 mako.config.json
  • 测试

    • 新增测试脚本 expect.js,简化了 Jest 测试环境的设置。

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

在此次拉取请求中,mako crate 的多个文件进行了更新,主要涉及模块转换和处理。新增了 amd_define_overrides 函数,并将其整合进 ModuleAst::Script 的转换流程中。同时,transform.rs 文件中的多个函数进行了修改,以支持异步依赖管理,并引入了新的功能以增强抽象语法树(AST)的处理。此外,新增了测试文件和配置文件,以支持 JavaScript 模块的测试和配置。

Changes

文件路径 更改摘要
crates/mako/src/build/transform.rs 添加了 amd_define_overrides 函数,并在转换过程中将其集成到 preset_folders 向量中。
crates/mako/src/generate/transform.rs 修改了 transform_alltransform_modulestransform_modules_in_thread 函数,支持异步依赖管理;新增 insert_swc_helper_replace 函数;更新了 transform_js_generate 函数以改善 AST 处理。
crates/mako/src/visitors.rs 新增公共模块声明 amd_define_overrides
crates/mako/src/visitors/amd_define_overrides.rs 新增 AmdDefineOverrides 结构体和 amd_define_overrides 函数;实现了 VisitMutFold 特性,修改特定的 UnaryExpr 节点。
e2e/fixtures/javascript.transform.amd/expect.js 新增用于测试 JavaScript 模块的功能,设置了简化的 Jest 测试环境。
e2e/fixtures/javascript.transform.amd/mako.config.json 新增空文件 mako.config.json
e2e/fixtures/javascript.transform.amd/src/a.ts 新增一个 IIFE,定义与 AMD 和 CommonJS 兼容的模块。
e2e/fixtures/javascript.transform.amd/src/index.ts 新增测试用例,检查从 ./a 导入的模块是否正确导出为 CommonJS 模块。

Possibly related PRs

在兔子洞里,变化飞舞,
新功能如花,绽放无数。
模块转换,异步依赖,
测试与配置,齐心协力。
让我们欢庆,共同跳跃,
兔子们欢呼,未来更美妙!
🐰✨


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

codecov bot commented Oct 15, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 55.62%. Comparing base (08c7e40) to head (ffca293).
Report is 17 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1642      +/-   ##
==========================================
+ Coverage   55.57%   55.62%   +0.05%     
==========================================
  Files         172      173       +1     
  Lines       17415    17498      +83     
==========================================
+ Hits         9678     9733      +55     
- Misses       7737     7765      +28     

☔ 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: 4

🧹 Outside diff range and nitpick comments (6)
e2e/fixtures/javascript.transform.amd/src/index.ts (2)

1-1: 考虑移除 @ts-ignore 注释

@ts-ignore 注释会抑制 TypeScript 的类型检查,这可能会隐藏潜在的问题。建议重新评估是否真的需要使用此注释。如果确实需要,请考虑使用更具体的 @ts-expect-error 并添加解释性注释。


4-6: 测试用例看起来不错,但可以稍作改进

测试用例正确地验证了导入的 'a' 是否等于预期值 1,这很好。测试描述也准确地表达了测试的目的。

为了提高可读性和可维护性,建议添加一个简短的注释来解释为什么期望 'a' 的值为 1。例如:

it("amd/umd should be exports as commonjs", () => {
  // 'a' should be 1 because ... (add explanation here)
  expect(a).toEqual(1)
});
e2e/fixtures/javascript.transform.amd/expect.js (1)

4-4: 建议为Jest注入添加错误处理

injectSimpleJest() 的调用看起来没有问题,但是建议添加错误处理机制。这样可以在Jest环境设置失败时提供更好的反馈。

考虑使用 try-catch 块来捕获可能的错误:

try {
  injectSimpleJest();
} catch (error) {
  console.error('Failed to inject Jest:', error);
  process.exit(1);
}
e2e/fixtures/javascript.transform.amd/src/a.ts (1)

1-1: 重新考虑使用 @ts-nocheck

文件顶部的 @ts-nocheck 注释禁用了所有 TypeScript 检查。这可能会导致潜在的类型相关问题被忽视。

建议重新考虑使用 @ts-nocheck。如果可能的话,尝试解决 TypeScript 报告的具体问题,而不是完全禁用类型检查。这将有助于提高代码的类型安全性和可维护性。

packages/mako/src/binding.d.ts (2)

60-64: 新增的转换方法增强了模块处理能力

这些新增的方法很好地扩展了 JsHooks 接口的功能:

  1. transform 方法允许对内容进行转换,这与PR的目标(改变UMD模块的导入方式)相符。
  2. transformInclude 方法提供了一种判断文件是否应该被转换的方式,这是一个有用的优化。

两个方法都支持异步操作,这对于可能耗时的转换操作来说是很好的。

为了提高可读性,建议为 transform 方法的参数和返回值使用类型别名。例如:

type TransformInput = { content: string; type: 'css' | 'js' };
type TransformOutput = { content: string; type: 'css' | 'js' } | void;

transform?: (content: TransformInput, path: string) => Promise<TransformOutput> | TransformOutput;

这样可以使方法签名更加清晰和易于理解。


81-84: 新增的 TransformResult 接口提供了清晰的转换结果结构

TransformResult 接口的添加是一个很好的改进,它为转换结果提供了明确的结构。这有助于提高代码的可读性和类型安全性。

为了保持一致性和增加类型安全性,建议将 type 属性的类型从 string 改为更具体的联合类型,以匹配 JsHooks 接口中 transform 方法的定义。例如:

export interface TransformResult {
  content: string;
  type: 'css' | 'js';
}

这样可以确保 TransformResulttransform 方法的返回类型保持一致,并防止可能的类型错误。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 08c7e40 and cac44f0.

📒 Files selected for processing (9)
  • crates/mako/src/build/transform.rs (2 hunks)
  • crates/mako/src/generate/transform.rs (0 hunks)
  • crates/mako/src/visitors.rs (1 hunks)
  • crates/mako/src/visitors/amd_define_overrides.rs (1 hunks)
  • e2e/fixtures/javascript.transform.amd/expect.js (1 hunks)
  • e2e/fixtures/javascript.transform.amd/mako.config.json (1 hunks)
  • e2e/fixtures/javascript.transform.amd/src/a.ts (1 hunks)
  • e2e/fixtures/javascript.transform.amd/src/index.ts (1 hunks)
  • packages/mako/src/binding.d.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • crates/mako/src/generate/transform.rs
✅ Files skipped from review due to trivial changes (1)
  • e2e/fixtures/javascript.transform.amd/mako.config.json
🧰 Additional context used
🔇 Additional comments (9)
e2e/fixtures/javascript.transform.amd/src/index.ts (1)

2-2: 导入语句看起来没有问题

导入语句使用了正确的 ES6 语法,从相对路径 './a' 导入模块 'a'。这符合现代 JavaScript/TypeScript 的最佳实践。

e2e/fixtures/javascript.transform.amd/expect.js (1)

1-2: 导入语句和构建结果解析看起来不错!

导入测试工具函数和使用 parseBuildResult 获取分发目录的方法是很好的做法。这种方法提高了代码的灵活性和可维护性。

e2e/fixtures/javascript.transform.amd/src/a.ts (1)

11-13: 模块定义看起来没有问题

模块定义简单明了,返回值为 1。实现正确,没有明显问题。

crates/mako/src/visitors.rs (1)

1-1: 新模块声明看起来符合PR的目标。

新增的amd_define_overrides模块声明与PR的目标一致,即修改UMD模块的导入方式。这个更改看起来是合理的。

请运行以下脚本来验证新模块的实现:

packages/mako/src/binding.d.ts (1)

Line range hint 1-84: 总体评价:代码变更增强了模块转换系统,符合PR目标

这些更改很好地增强了模块转换系统的功能:

  1. 新增的 transformtransformInclude 方法为内容转换提供了灵活的机制。
  2. TransformResult 接口的引入提供了清晰的转换结果结构。

这些变更与PR的目标(改变UMD模块的导入方式)相符,并为未来的扩展提供了良好的基础。

建议的小改进(类型定义的细化)可以进一步提高代码的清晰度和类型安全性,但总的来说,这些更改是积极的,并且与项目目标很好地保持一致。

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

250-250: 验证 AMD 定义覆盖的影响

添加 amd_define_overrides() 转换步骤符合 PR 的目标,即将 UMD 模块作为 CommonJS 模块导入。这个改变可能会影响代码与 AMD 加载器或 UMD 模块的交互方式。

建议:

  1. 确保这个改变不会对依赖 AMD 加载的现有代码产生负面影响。
  2. 在不同的环境中测试受影响的模块,特别是在浏览器和 Node.js 环境中。
  3. 验证这个改变是否正确地处理了所有的 UMD 模块场景。

运行以下脚本来检查可能受影响的文件:

请根据脚本的输出结果,确保这些文件在新的转换过程中能够正确工作。

✅ Verification successful

验证通过:影响范围有限

此次添加 amd_define_overrides() 仅影响了 e2e/fixtures/config.umd/expect.js 文件。请确认此更改在该文件中的应用是预期的,并确保不会引入任何回归问题。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:搜索可能受 AMD 定义覆盖影响的文件

# 测试:搜索包含 AMD 定义的文件
echo "包含 AMD 定义的文件:"
rg --type js "typeof\s+define\s*===?\s*['\"]function['\"]\s*&&\s*define\.amd"

# 测试:搜索使用 UMD 模式的文件
echo "使用 UMD 模式的文件:"
rg --type js "(typeof\s+define\s*===?\s*['\"]function['\"]\s*&&\s*define\.amd|typeof\s+exports\s*===?\s*['\"]object['\"]\s*\|\|\s*typeof\s+module\s*!==?\s*['\"]undefined['\"]\s*&&\s*module\.exports)"

Length of output: 599

crates/mako/src/visitors/amd_define_overrides.rs (3)

5-6: 结构体命名与功能一致

AmdDefineOverrides 结构体命名清晰,符合其职责。


7-9: 函数返回类型与实现一致性验证

amd_define_overrides 函数的返回类型声明为 impl VisitMut + Fold,但当前只实现了 VisitMut,未直接实现 Fold。请确认是否需要同时实现 Fold trait,或者调整返回类型以准确反映实现。


29-36: 确认逻辑与条件的完整处理

当前代码仅在匹配到 typeof define === 'function' 时,将整个条件替换为 false,但未检查逻辑与 && 的右侧条件 define.amd。请确认是否需要同时考虑并处理右侧条件,以确保对条件的修改不会影响其他逻辑。

运行以下脚本以查找代码库中使用 define.amd 的情况,验证是否需要处理右侧条件:

这将帮助确定是否需要在修改中考虑右侧条件。

const { distDir } = parseBuildResult(__dirname);

injectSimpleJest()
require(path.join(distDir, 'index.js'));
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

建议导入path模块并添加错误处理

使用 path.join 来构建文件路径是一个很好的做法,但是有几点需要改进:

  1. path 模块没有在文件开头导入。
  2. 缺少模块加载失败时的错误处理。

建议进行以下修改:

  1. 在文件开头添加 path 模块的导入:
const path = require('path');
  1. 为模块加载添加错误处理:
try {
  require(path.join(distDir, 'index.js'));
} catch (error) {
  console.error('Failed to load module:', error);
  process.exit(1);
}

Comment on lines 12 to 38
fn visit_mut_if_stmt(&mut self, node: &mut IfStmt) {
if let box Expr::Bin(BinExpr {
op: BinaryOp::LogicalAnd,
left:
box Expr::Bin(BinExpr {
op: BinaryOp::EqEqEq,
left:
box Expr::Unary(UnaryExpr {
op: UnaryOp::TypeOf,
arg: box Expr::Ident(Ident { sym, .. }),
..
}),
..
}),
..
}) = &node.test
{
if sym == "define" {
node.test = Box::new(Expr::Ident(Ident {
span: DUMMY_SP,
ctxt: SyntaxContext::empty(),
sym: "false".into(),
optional: false,
}));
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议重构复杂的模式匹配以提高代码可读性

visit_mut_if_stmt 方法中,模式匹配嵌套层级较深,可能影响代码的可读性和维护性。建议考虑以下改进:

  • 使用辅助函数或闭包来拆分复杂的匹配条件。
  • 采用更简洁的模式匹配方式,如使用 if let 多重匹配或匹配守卫。

这将有助于其他开发者更容易理解代码逻辑。

@stormslowly
Copy link
Member

stormslowly commented Oct 15, 2024

变成

if ( "undefined" === 'function' && define.amd) {
        define(xxx);
    } 

是不是更简单

use swc_core::ecma::ast::*;
use swc_core::ecma::visit::{as_folder, Fold, VisitMut};

pub struct AmdDefineOverrides {}
Copy link
Member

Choose a reason for hiding this comment

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

这个 struct 需要 unresolve 的 mark 的

Copy link
Member

@stormslowly stormslowly left a comment

Choose a reason for hiding this comment

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

ok to me

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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cac44f0 and ffca293.

📒 Files selected for processing (3)
  • crates/mako/src/build/transform.rs (2 hunks)
  • crates/mako/src/visitors/amd_define_overrides.rs (1 hunks)
  • e2e/fixtures/javascript.transform.amd/expect.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/mako/src/build/transform.rs
  • e2e/fixtures/javascript.transform.amd/expect.js
🧰 Additional context used
🔇 Additional comments (2)
crates/mako/src/visitors/amd_define_overrides.rs (2)

15-24: 实现逻辑清晰,符合预期

VisitMut 接口的实现正确地处理了 UnaryExpr,代码简洁明了,逻辑正确。


26-82: 测试用例完善,验证了关键功能

测试模块包含了主要功能的测试用例,确保了代码的正确性和稳定性。

Comment on lines +7 to +9
pub struct AmdDefineOverrides {
unresolved_mark: Mark,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

为公共结构体添加文档注释

AmdDefineOverrides 结构体是公共的,建议添加文档注释,以提高代码的可读性和维护性。

Comment on lines +11 to +13
pub fn amd_define_overrides(unresolved_mark: Mark) -> impl VisitMut + Fold {
as_folder(AmdDefineOverrides { unresolved_mark })
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

为公共函数添加文档注释

amd_define_overrides 函数是公共的,建议添加文档注释,解释其功能和使用场景,以便其他开发者了解其作用。

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.

3 participants