Skip to content

Commit e68720a

Browse files
authoredDec 23, 2023
fix(es): Apply paren_remover for minify (#8442)
**Related issue:** - Closes #8437
1 parent 4564a01 commit e68720a

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
 

‎crates/swc/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ use swc_ecma_transforms::{
147147
pass::noop,
148148
resolver,
149149
};
150+
use swc_ecma_transforms_base::fixer::paren_remover;
150151
use swc_ecma_visit::{FoldWith, VisitMutWith, VisitWith};
151152
pub use swc_error_reporters::handler::{try_with_handler, HandlerOpts};
152153
pub use swc_node_comments::SwcComments;
@@ -865,6 +866,8 @@ impl Compiler {
865866
let is_mangler_enabled = min_opts.mangle.is_some();
866867

867868
let module = self.run_transform(handler, false, || {
869+
let module = module.fold_with(&mut paren_remover(Some(&comments)));
870+
868871
let module =
869872
module.fold_with(&mut resolver(unresolved_mark, top_level_mark, false));
870873

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import swc from "../../..";
2+
3+
it("should output same result", async () => {
4+
const origin = `
5+
function toFixed(value, maxDecimals, roundingFunction, optionals) {
6+
var splitValue = value.toString().split('.'),
7+
minDecimals = maxDecimals - (optionals || 0),
8+
9+
optionalsRegExp,
10+
power,
11+
output;
12+
var boundedPrecisions;
13+
// var unused = 'xxxx';
14+
15+
// Use the smallest precision value possible to avoid errors from floating point representation
16+
if (splitValue.length === 2) {
17+
boundedPrecisions = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals);
18+
} else {
19+
boundedPrecisions = minDecimals;
20+
}
21+
22+
power = Math.pow(10, boundedPrecisions);
23+
24+
// Multiply up by precision, round accurately, then divide and use native toFixed():
25+
output = (roundingFunction(value + 'e+' + boundedPrecisions) / power).toFixed(boundedPrecisions);
26+
27+
if (optionals > maxDecimals - boundedPrecisions) {
28+
optionalsRegExp = new RegExp('\\.?0{1,' + (optionals - (maxDecimals - boundedPrecisions)) + '}$');
29+
output = output.replace(optionalsRegExp, '');
30+
}
31+
32+
return output;
33+
}
34+
toFixed(1.2345, 2, Math.round, 1);
35+
`
36+
37+
async function minify() {
38+
const { code } = await swc.minify(origin, {
39+
compress: true,
40+
mangle: false
41+
});
42+
return code;
43+
}
44+
45+
async function transform() {
46+
const { code } = await swc.transform(origin, {
47+
jsc: {
48+
minify: {
49+
compress: true,
50+
mangle: false
51+
},
52+
},
53+
isModule: false,
54+
minify: true
55+
});
56+
return code;
57+
}
58+
59+
const [minifyResult, transformResult] = await Promise.all([minify(), transform()]);
60+
expect(minifyResult).toEqual(transformResult);
61+
});

0 commit comments

Comments
 (0)
Please sign in to comment.