Skip to content

Commit

Permalink
fix(es): Apply paren_remover for minify (#8442)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #8437
  • Loading branch information
Austaras authored Dec 23, 2023
1 parent 4564a01 commit e68720a
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
3 changes: 3 additions & 0 deletions crates/swc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ use swc_ecma_transforms::{
pass::noop,
resolver,
};
use swc_ecma_transforms_base::fixer::paren_remover;
use swc_ecma_visit::{FoldWith, VisitMutWith, VisitWith};
pub use swc_error_reporters::handler::{try_with_handler, HandlerOpts};
pub use swc_node_comments::SwcComments;
Expand Down Expand Up @@ -865,6 +866,8 @@ impl Compiler {
let is_mangler_enabled = min_opts.mangle.is_some();

let module = self.run_transform(handler, false, || {
let module = module.fold_with(&mut paren_remover(Some(&comments)));

let module =
module.fold_with(&mut resolver(unresolved_mark, top_level_mark, false));

Expand Down
61 changes: 61 additions & 0 deletions node-swc/__tests__/minify/issue_8437_test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import swc from "../../..";

it("should output same result", async () => {
const origin = `
function toFixed(value, maxDecimals, roundingFunction, optionals) {
var splitValue = value.toString().split('.'),
minDecimals = maxDecimals - (optionals || 0),
optionalsRegExp,
power,
output;
var boundedPrecisions;
// var unused = 'xxxx';
// Use the smallest precision value possible to avoid errors from floating point representation
if (splitValue.length === 2) {
boundedPrecisions = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals);
} else {
boundedPrecisions = minDecimals;
}
power = Math.pow(10, boundedPrecisions);
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value + 'e+' + boundedPrecisions) / power).toFixed(boundedPrecisions);
if (optionals > maxDecimals - boundedPrecisions) {
optionalsRegExp = new RegExp('\\.?0{1,' + (optionals - (maxDecimals - boundedPrecisions)) + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
toFixed(1.2345, 2, Math.round, 1);
`

async function minify() {
const { code } = await swc.minify(origin, {
compress: true,
mangle: false
});
return code;
}

async function transform() {
const { code } = await swc.transform(origin, {
jsc: {
minify: {
compress: true,
mangle: false
},
},
isModule: false,
minify: true
});
return code;
}

const [minifyResult, transformResult] = await Promise.all([minify(), transform()]);
expect(minifyResult).toEqual(transformResult);
});

0 comments on commit e68720a

Please sign in to comment.