Skip to content

Commit

Permalink
feat(minifier): implement folding simple arrow fns (#6875)
Browse files Browse the repository at this point in the history
basically
```ts
const foo = () => {
    return baz
}
```
becomes
```ts
const foo = () => baz
```
  • Loading branch information
camc314 committed Oct 25, 2024
1 parent a73c5af commit 860cbca
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,26 @@ impl<'a> Traverse<'a> for PeepholeSubstituteAlternateSyntax {
self.changed = true;
}
}
// `() => { return foo })` -> `() => foo`
Expression::ArrowFunctionExpression(arrow_expr) => {
if !arrow_expr.expression
&& arrow_expr.body.directives.is_empty()
&& arrow_expr.body.statements.len() == 1
{
if let Some(body) = arrow_expr.body.statements.first_mut() {
if let Statement::ReturnStatement(ret_stmt) = body {
let return_stmt_arg =
ret_stmt.argument.as_mut().map(|arg| ctx.ast.move_expression(arg));

if let Some(return_stmt_arg) = return_stmt_arg {
*body = ctx.ast.statement_expression(SPAN, return_stmt_arg);
arrow_expr.expression = true;
self.changed = true;
}
}
}
}
}
_ => {}
}
}
Expand Down Expand Up @@ -963,4 +983,10 @@ mod test {
test("1/x * (y/1 * (1/z))", "1/x * (y/1) * (1/z)");
test_same("1/x * (y/1) * (1/z)");
}

#[test]
fn test_fold_arrow_function_return() {
test("const foo = () => { return 'baz' }", "const foo = () => 'baz'");
test_same("const foo = () => { foo; return 'baz' }");
}
}
2 changes: 1 addition & 1 deletion tasks/minsize/minsize.snap
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Original | Minified | esbuild | Gzip | esbuild

555.77 kB | 276.49 kB | 270.13 kB | 91.15 kB | 90.80 kB | d3.js

1.01 MB | 467.63 kB | 458.89 kB | 126.75 kB | 126.71 kB | bundle.min.js
1.01 MB | 467.60 kB | 458.89 kB | 126.74 kB | 126.71 kB | bundle.min.js

1.25 MB | 662.86 kB | 646.76 kB | 164.00 kB | 163.73 kB | three.js

Expand Down

0 comments on commit 860cbca

Please sign in to comment.