From a62eaa0d3be131c7b2d06de5ee175fd2c844543f Mon Sep 17 00:00:00 2001 From: Rafael Oleza Date: Sun, 25 Feb 2018 10:31:06 -0800 Subject: [PATCH] Make the inline platform transform support string keys Summary: This diff makes the platform inline transformer support string keys, for example: ``` Platform.select({ 'ios': 'ios', 'default': 'default', }); ``` This fixes https://github.com/facebook/metro/issues/134 Reviewed By: mjesun Differential Revision: D7079013 fbshipit-source-id: 3e47bb4a28f2ac776475842982e089d5954d6521 --- .../JSTransformer/worker/__tests__/inline-test.js | 10 ++++++++++ packages/metro/src/JSTransformer/worker/inline.js | 12 +++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/metro/src/JSTransformer/worker/__tests__/inline-test.js b/packages/metro/src/JSTransformer/worker/__tests__/inline-test.js index bf84c525..a6c1a85e 100644 --- a/packages/metro/src/JSTransformer/worker/__tests__/inline-test.js +++ b/packages/metro/src/JSTransformer/worker/__tests__/inline-test.js @@ -186,6 +186,16 @@ describe('inline constants', () => { ); }); + it('inlines Platform.select in the code when using string keys', () => { + const code = `function a() { + var a = Platform.select({'ios': 1, 'android': 2}); + }`; + const {ast} = inline('arbitrary.js', {code}, {platform: 'android'}); + expect(toString(ast)).toEqual( + normalize(code.replace(/Platform\.select[^;]+/, '2')), + ); + }); + it('replaces Platform.select in the code if Platform is a top level import', () => { const code = ` var Platform = require('Platform'); diff --git a/packages/metro/src/JSTransformer/worker/inline.js b/packages/metro/src/JSTransformer/worker/inline.js index 2c188c39..d46cdf45 100644 --- a/packages/metro/src/JSTransformer/worker/inline.js +++ b/packages/metro/src/JSTransformer/worker/inline.js @@ -49,7 +49,17 @@ const isDev = (node, parent, scope) => !t.isMemberExpression(parent); function findProperty(objectExpression, key, fallback) { - const property = objectExpression.properties.find(p => p.key.name === key); + const property = objectExpression.properties.find(p => { + if (t.isIdentifier(p.key) && p.key.name === key) { + return true; + } + + if (t.isStringLiteral(p.key) && p.key.value === key) { + return true; + } + + return false; + }); return property ? property.value : fallback(); }