Skip to content

Commit 99aaae5

Browse files
vitorbalfkling
authored andcommittedMar 7, 2018
Fix renameTo not taking property shorthands into account (#211)
* Fix `renameTo` not taking property shorthands into account This fixes the `renameTo` helper method not properly renaming object properties that are shorthands. The previous version of the code would rename the property's `value` correctly, but since `shorthand` was still set as `true`, the output result would still be the old variable as a shorthand property. Now, if an identifier to be renamed is of type `Property` and is a shorthand (but not a method), we flip the `shorthand` value to be `false`. * babel -> getParser() * Add comment that explains why this works
1 parent e60662b commit 99aaae5

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
 

‎src/collections/VariableDeclarator.js

+15
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,21 @@ const transformMethods = {
134134
scope = scope.parent;
135135
}
136136
if (scope) { // identifier must refer to declared variable
137+
138+
// It may look like we filtered out properties,
139+
// but the filter only ignored property "keys", not "value"s
140+
// In shorthand properties, "key" and "value" both have an
141+
// Identifier with the same structure.
142+
const parent = path.parent.node;
143+
if (
144+
types.Property.check(parent) &&
145+
parent.shorthand &&
146+
!parent.method
147+
) {
148+
149+
path.parent.get('shorthand').replace(false);
150+
}
151+
137152
path.get('name').replace(newName);
138153
}
139154
});

‎src/collections/__tests__/VariableDeclarator-test.js

+31
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,37 @@ describe('VariableDeclarators', function() {
128128

129129
expect(identifiers.length).toBe(1);
130130
});
131+
132+
it('properly renames a shorthand property that was using the old variable name', function() {
133+
nodes = [recast.parse([
134+
'var foo = 42;',
135+
'var obj2 = {',
136+
' foo,',
137+
'};',
138+
].join('\n'), {parser: getParser()}).program];
139+
140+
// Outputs:
141+
// var newFoo = 42;
142+
// var obj2 = {
143+
// foo: newFoo,
144+
// };
145+
Collection.fromNodes(nodes)
146+
.findVariableDeclarators('foo').renameTo('newFoo');
147+
148+
expect(
149+
Collection.fromNodes(nodes).find(types.Identifier, { name: 'newFoo' }).length
150+
).toBe(2);
151+
expect(
152+
Collection.fromNodes(nodes).find(types.Identifier, { name: 'foo' }).length
153+
).toBe(1);
154+
155+
expect(
156+
Collection.fromNodes(nodes).find(types.Property).filter(prop => !prop.value.shorthand).length
157+
).toBe(1);
158+
expect(
159+
Collection.fromNodes(nodes).find(types.Property).filter(prop => prop.value.shorthand).length
160+
).toBe(0);
161+
});
131162

132163
it('does not rename React component prop name', function () {
133164
const declarators = Collection.fromNodes(nodes)

0 commit comments

Comments
 (0)
Please sign in to comment.