Skip to content

Commit 6acf084

Browse files
committed
fix: keep value when inlining variable (#101)
1 parent 0b619e5 commit 6acf084

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

packages/webcrack/src/ast-utils/inline.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,11 @@ export function inlineVariable(
4646
binding.referencePaths.forEach((ref) => {
4747
ref.replaceWith(assignment.node.right);
4848
});
49-
assignment.remove();
49+
if (assignment.parentPath.isExpressionStatement()) {
50+
assignment.remove();
51+
} else {
52+
assignment.replaceWith(assignment.node.right);
53+
}
5054
binding.path.remove();
5155
}
5256
}

packages/webcrack/src/ast-utils/test/inline.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ test('inline variable with assignment', () => {
3131
expect(ast).toMatchInlineSnapshot(`let b = 1;`);
3232
});
3333

34+
test('inline variable with assignment in an expression', () => {
35+
const ast = parse('let a; x = a = 1; let b = a;');
36+
traverse(ast, {
37+
Program(path) {
38+
const binding = path.scope.getBinding('a')!;
39+
inlineVariable(binding, undefined, true);
40+
},
41+
});
42+
expect(ast).toMatchInlineSnapshot(`
43+
x = 1;
44+
let b = 1;
45+
`);
46+
});
47+
3448
test('inline array elements', () => {
3549
const ast = parse('const arr = ["foo", "bar"]; console.log(arr[0]);');
3650
traverse(ast, {

0 commit comments

Comments
 (0)