Skip to content

Commit a4bdfc4

Browse files
vzaidmanfacebook-github-bot
authored andcommitted
Clone ObjectMethod before toExpression in preset
Summary: The React Native Babel preset replaces `Platform.select({...})` with the selected property during production transforms. When the selected property is an object method, converting it to an expression mutates the node in place. Since the replacement is computed before the purity check, bailing out on an impure sibling leaves the mutated method behind, producing invalid output. Clone the method before converting it. Also assess purity on the property itself: an `ObjectMethod` has no value, so checking the value treated every method as impure and skipped inlining. ## Changelog: [GENERAL] [FIXED] - Fix Platform.select inlining producing invalid output for object methods when discarding impure initializers is skipped Reviewed By: GijsWeterings Differential Revision: D119305530
1 parent b87344e commit a4bdfc4

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

packages/react-native-babel-preset/src/__tests__/inline-platform-plugin-test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,15 @@ describe('Platform.select', () => {
493493
`);
494494
});
495495

496+
test('does not mutate object methods when bailing out on impure initializers', () => {
497+
expectUnchanged(`
498+
const value = require('react-native').Platform.select({
499+
ios() { return 1; },
500+
android: sideEffect(),
501+
});
502+
`);
503+
});
504+
496505
test('does not inline computed keys', () => {
497506
expect(select('{[key]: 1, default: 2}')).toContain('Platform.select');
498507
});

packages/react-native-babel-preset/src/inline-platform-plugin.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,9 @@ module.exports = function inlinePlatformPlugin(
443443
if (t.isObjectProperty(property)) {
444444
return property.value;
445445
}
446-
return t.toExpression(property);
446+
// Clone: toExpression mutates in place, e.g. `ios() {}` would be
447+
// left mutated if the purity check below bails out.
448+
return t.toExpression(t.cloneNode(property));
447449
}
448450
}
449451
return fallback();

0 commit comments

Comments
 (0)