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: commonjs may miss use strict directive #1386

Merged
merged 8 commits into from
Jul 10, 2024
Merged

Conversation

Jinbao1001
Copy link
Member

@Jinbao1001 Jinbao1001 commented Jul 8, 2024

https://www.unpkg.com/browse/[email protected]/lib/core/Axios.js L30-L35
webpack 编译正常执行,mako 会导致 config.url 成为一个对象,期望是 String
原因 webpack 保留了use strict

对于ESM模块,默认情况下,所有模块都是以严格模式(strict mode)运行的,这是ESM规范的一部分。因此,即使源代码中没有明确写入"use strict",加载和执行ESM模块时也会自动采用严格模式, 这里也按照规范给所有的esm添加了 use strict 指令

close #839

Summary by CodeRabbit

  • 新增功能

    • 引入一个新的模块Commonjs,实现了VisitMut接口,用于处理CommonJS模块的转换。
    • 在新的文件expect.js中,添加了解析构建结果和断言内容匹配特定模块模式的功能。
    • 在新的文件index.tsscripts.ts中,添加了一个可以配置并返回修改后的config对象的函数。
  • 重构

    • optimize_define_utils.rs中,重构了visit_mut_module_items方法,使用新函数来判断语句是否为指令。
  • 文档

    • 添加了新的配置文件mako.config.json

Copy link
Contributor

coderabbitai bot commented Jul 8, 2024

Walkthrough

本次变更主要集中在对 mako 的模块转换和优化逻辑做出调整,删除过时的配置项和功能标志,改进公共模块处理逻辑,并引入新的函数来判断 directive 语句。这些改动旨在改进模块处理的准确性和性能,特别是在 CommonJS 模块处理和指令保留方面。

Changes

文件路径 变更摘要
crates/mako/src/generate/transform.rs 删除和调整与模块转换相关的导入,改进 common_js 函数调用。
crates/mako/src/visitors/common_js.rs 新增 Commonjs 模块,实现 VisitMut 以处理 CommonJS 模块。
crates/mako/src/visitors/mod.rs 向公开导出的模块列表中添加 common_js 模块。
crates/mako/src/visitors/optimize_define_utils.rs 导入 StmtStr,重构 visit_mut_module_items 方法,引入新函数 is_stmt_directive
e2e/fixtures/javascript.transform.commonjs/expect.js 新增文件,解析构建结果并进行断言。
e2e/fixtures/javascript.transform.commonjs/index.ts 新增函数 fn,操作 config 对象并返回修改后的对象。
e2e/fixtures/javascript.transform.commonjs/mako.config.json 新增空 JSON 配置文件 {}
e2e/fixtures/javascript.transform.commonjs/scripts.ts 新增函数 fn,操作 config 对象,并包含一个使用示例。
e2e/fixtures/generate.chunks-hash-replace/expect.js 更新文件路径引用中的哈希值。

Assessment against linked issues

Objective Addressed Explanation
保留编译后的 directive 语句 (#839)

Poem

在代码的森林深处,
模块转换在跳舞,
指令不再迷路,
逻辑清晰如露珠,
CommonJS 间穿梭,
提升性能没得说。
🐰✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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 (1)
crates/mako/src/visitors/common_js.rs (1)

20-53: 实现逻辑看起来不错,但请翻译注释。

VisitMut trait 的实现正确地转换了模块并应用了必要的配置。然而,为了保持一致性,建议将中文注释翻译成英文。

-                // NOTE: 这里后面要调整为注入自定义require
+                // NOTE: This needs to be adjusted later to inject custom require
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3e1417a and 77cbf0b.

Files selected for processing (6)
  • crates/mako/src/generate/transform.rs (3 hunks)
  • crates/mako/src/visitors/common_js.rs (1 hunks)
  • crates/mako/src/visitors/mod.rs (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/expect.js (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/index.ts (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/mako.config.json (1 hunks)
Files skipped from review due to trivial changes (5)
  • crates/mako/src/generate/transform.rs
  • crates/mako/src/visitors/mod.rs
  • e2e/fixtures/javascript.transform.commonjs/expect.js
  • e2e/fixtures/javascript.transform.commonjs/index.ts
  • e2e/fixtures/javascript.transform.commonjs/mako.config.json
Additional comments not posted (3)
crates/mako/src/visitors/common_js.rs (3)

1-12: 导入部分看起来不错。

这些导入包含了模块转换和实用函数所需的依赖项,适合当前实现的功能。


14-18: 结构体定义看起来不错。

Commonjs 结构体定义了三个字段:context, unresolved_mark, 和 import_interop,清晰且适当。


56-66: 函数定义看起来不错。

common_js 函数定义明确且适当,返回一个带有提供参数的 Commonjs 实例。


impl VisitMut for Commonjs {
fn visit_mut_module(&mut self, n: &mut Module) {
let use_strict = n
Copy link
Member

Choose a reason for hiding this comment

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

这个判断不准确 directive 需要是 module 的最开始的string

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 77cbf0b and 20554f1.

Files selected for processing (5)
  • crates/mako/src/visitors/common_js.rs (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/expect.js (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/index.ts (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/mako.config.json (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/scripts.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • e2e/fixtures/javascript.transform.commonjs/mako.config.json
Files skipped from review as they are similar to previous changes (2)
  • e2e/fixtures/javascript.transform.commonjs/expect.js
  • e2e/fixtures/javascript.transform.commonjs/index.ts
Additional comments not posted (1)
crates/mako/src/visitors/common_js.rs (1)

39-61: 确保配置项的正确性

在设置 Config 时,确保所有配置项都符合预期,特别是 allow_top_level_thisstrict_mode 的设置。

请确认 allow_top_level_thisstrict_mode 的设置是否符合预期,特别是在 ESM 模式下。

Comment on lines +8 to +9
// @ts-ignore
fn('url', { method: 'get' }).url.indexOf('u')
Copy link
Contributor

Choose a reason for hiding this comment

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

避免忽略 TypeScript 错误

@ts-ignore 注释会忽略 TypeScript 错误,可能会掩盖潜在的问题。建议修复类型错误而不是忽略它们。

// @ts-ignore
fn('url', { method: 'get' }).url.indexOf('u');

Comment on lines +21 to +37
fn visit_mut_module(&mut self, n: &mut Module) {
let mut use_strict = false;
if utils::is_esm(n) {
use_strict = true
} else {
for item in n.body.iter() {
if let Some(stmt) = item.as_stmt() {
if stmt.is_directive() {
if stmt.is_use_strict() {
use_strict = true;
}
} else {
break;
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

优化 "use strict" 指令检查

目前的实现会遍历整个模块的 body 来查找 "use strict" 指令。可以优化为只检查模块的开头部分。

fn visit_mut_module(&mut self, n: &mut Module) {
    let mut use_strict = false;
    for item in n.body.iter().take_while(|item| item.is_directive()) {
        if let Some(stmt) = item.as_stmt() {
            if stmt.is_use_strict() {
                use_strict = true;
                break;
            }
        }
    }
    ...
}

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 (1)
crates/mako/src/visitors/optimize_define_utils.rs (1)

158-173: 新函数实现合理,但可以改进可读性

函数 is_directive_judged_by_stmt_value_and_raw 实现了根据语句的值和原始字符串判断是否为指令的逻辑,符合保留 use strict 等指令的目标。

为了提高可读性,可以将嵌套的 match 语句改为更清晰的逻辑结构:

fn is_directive_judged_by_stmt_value_and_raw(stmt: Stmt) -> bool {
    match stmt.as_ref() {
        Some(Stmt::Expr(expr)) => match &*expr.expr {
            Expr::Lit(Lit::Str(Str { raw: Some(raw), .. })) => {
                raw.starts_with("\"use ") || raw.starts_with("'use ")
            }
            Expr::Lit(Lit::Str(Str { value: v, raw: None, .. })) => {
                v.to_string().starts_with("use ")
            }
            _ => false,
        },
        _ => false,
    }
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 20554f1 and 8ef4736.

Files selected for processing (3)
  • crates/mako/src/visitors/optimize_define_utils.rs (3 hunks)
  • e2e/fixtures/generate.chunks-hash-replace/expect.js (1 hunks)
  • e2e/fixtures/javascript.transform.commonjs/scripts.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • e2e/fixtures/generate.chunks-hash-replace/expect.js
Files skipped from review as they are similar to previous changes (1)
  • e2e/fixtures/javascript.transform.commonjs/scripts.ts
Additional comments not posted (1)
crates/mako/src/visitors/optimize_define_utils.rs (1)

2-2: 导入语句添加合理

添加了 StmtStr 的导入,这些导入在新函数 is_directive_judged_by_stmt_value_and_raw 中使用。

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8ef4736 and 66df08c.

Files selected for processing (1)
  • crates/mako/src/visitors/optimize_define_utils.rs (3 hunks)
Files skipped from review due to trivial changes (1)
  • crates/mako/src/visitors/optimize_define_utils.rs

@stormslowly stormslowly changed the title fix: comonjs may miss use strict directive fix: commonjs may miss use strict directive Jul 10, 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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 66df08c and 07e52d5.

Files selected for processing (1)
  • crates/mako/src/visitors/optimize_define_utils.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • crates/mako/src/visitors/optimize_define_utils.rs

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 07e52d5 and ae03f19.

Files selected for processing (1)
  • crates/mako/src/visitors/optimize_define_utils.rs (2 hunks)
Files skipped from review due to trivial changes (1)
  • crates/mako/src/visitors/optimize_define_utils.rs

@stormslowly stormslowly merged commit 60b45d2 into master Jul 10, 2024
8 checks passed
@afc163 afc163 deleted the fix/strict_mode branch July 10, 2024 15:17
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.

文件中的 directive 编译后消失
2 participants