Skip to content

Commit

Permalink
feat: rename imports
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Feb 19, 2024
1 parent 0ebbeb2 commit 271f21c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 15 deletions.
39 changes: 24 additions & 15 deletions packages/webcrack/src/unminify/test/rename-destructuring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ test('ignore same key and alias', () =>
dispatchers: dispatchers,
} = n;
`).toMatchInlineSnapshot(`
const {
gql,
dispatchers
} = n;
`));
const {
gql,
dispatchers
} = n;
`));

test('rename object destructuring with conflict', () =>
expectJS(`
Expand Down Expand Up @@ -73,19 +73,28 @@ test('rename object destructuring with global variable conflict', () =>
} = n;
Object.keys(t);
`).toMatchInlineSnapshot(`
const {
Object: _Object
} = n;
Object.keys(_Object);
`));
const {
Object: _Object
} = n;
Object.keys(_Object);
`));

test('rename object destructuring with reserved identifier', () =>
expectJS(`
const { delete: t } = n;
t();
`).toMatchInlineSnapshot(`
const {
delete: _delete
} = n;
_delete();
`));
const {
delete: _delete
} = n;
_delete();
`));

test('rename import', () =>
expectJS(`
import { render as a } from "preact";
a();
`).toMatchInlineSnapshot(`
import { render } from "preact";
render();
`));
16 changes: 16 additions & 0 deletions packages/webcrack/src/unminify/transforms/rename-destructuring.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as t from '@babel/types';
import * as m from '@codemod/matchers';
import { generateUid, renameFast, type Transform } from '../../ast-utils';

Expand Down Expand Up @@ -33,6 +34,21 @@ export default {
}
},
},
ImportSpecifier: {
exit(path) {
if (
t.isIdentifier(path.node.imported) &&
path.node.imported.name !== path.node.local.name
) {
const binding = path.scope.getBinding(path.node.local.name);
if (!binding) return;

const newName = generateUid(binding, path.node.imported.name);
renameFast(binding, newName);
this.changes++;
}
},
},
};
},
} satisfies Transform;

0 comments on commit 271f21c

Please sign in to comment.