From a317b9da6c2a09432bf1488cb350928000d8a3fa Mon Sep 17 00:00:00 2001 From: Alexey Kureev Date: Tue, 7 Feb 2017 04:26:45 -0800 Subject: [PATCH] Add default option for Platform.select Summary: satya164 asked me to take over fixes for [this PR](https://github.com/facebook/react-native/pull/11608), so here we go! Closes https://github.com/facebook/react-native/pull/12218 Differential Revision: D4515285 Pulled By: davidaurelio fbshipit-source-id: 8987c518401fc67093dfe93bbbb63b934c20f6f9 --- .../src/JSTransformer/worker/__tests__/inline-test.js | 9 +++++++++ .../metro-bundler/src/JSTransformer/worker/inline.js | 8 +++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/metro-bundler/src/JSTransformer/worker/__tests__/inline-test.js b/packages/metro-bundler/src/JSTransformer/worker/__tests__/inline-test.js index c97b7a97..821aaf4c 100644 --- a/packages/metro-bundler/src/JSTransformer/worker/__tests__/inline-test.js +++ b/packages/metro-bundler/src/JSTransformer/worker/__tests__/inline-test.js @@ -150,6 +150,15 @@ describe('inline constants', () => { expect(toString(ast)).toEqual(normalize(code.replace(/Platform\.select[^;]+/, '1'))); }); + it('inlines Platform.select in the code if Platform is a global and the argument doesn\'t have target platform in it\'s keys', () => { + const code = `function a() { + var a = Platform.select({ios: 1, default: 2}); + var b = a.Platform.select({ios: 1, default: 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-bundler/src/JSTransformer/worker/inline.js b/packages/metro-bundler/src/JSTransformer/worker/inline.js index c9bdee03..6b2bf5fb 100644 --- a/packages/metro-bundler/src/JSTransformer/worker/inline.js +++ b/packages/metro-bundler/src/JSTransformer/worker/inline.js @@ -96,9 +96,9 @@ const isDev = (node, parent, scope) => isGlobal(scope.getBinding(dev.name)) && !(t.isMemberExpression(parent)); -function findProperty(objectExpression, key) { +function findProperty(objectExpression, key, fallback) { const property = objectExpression.properties.find(p => p.key.name === key); - return property ? property.value : t.identifier('undefined'); + return property ? property.value : fallback(); } const inlinePlugin = { @@ -133,8 +133,10 @@ const inlinePlugin = { isPlatformSelect(node, scope, opts.isWrapped) || isReactPlatformSelect(node, scope, opts.isWrapped) ) { + const fallback = () => + findProperty(arg, 'default', () => t.identifier('undefined')); const replacement = t.isObjectExpression(arg) - ? findProperty(arg, opts.platform) + ? findProperty(arg, opts.platform, fallback) : node; path.replaceWith(replacement);