Skip to content

Commit

Permalink
fix(babel): fix unused platform code removal (#25171)
Browse files Browse the repository at this point in the history
# Why

Metro applies this plugin too but it does it after the imports have been
transformed which breaks the plugin. Here, we'll apply it before the
commonjs transform, in production, to ensure `Platform.OS` is replaced
with a string literal and `__DEV__` is converted to a boolean.
Applying early also means that web can be transformed before the
`react-native-web` transform mutates the import.

# Test Plan

- Added new tests for the plugin.

# Checklist

<!--
Please check the appropriate items below if they apply to your diff.
This is required for changes to Expo modules.
-->

- [ ] Documentation is up to date to reflect these changes (eg:
https://docs.expo.dev and README.md).
- [ ] Conforms with the [Documentation Writing Style
Guide](https://github.com/expo/expo/blob/main/guides/Expo%20Documentation%20Writing%20Style%20Guide.md)
- [ ] This diff will work correctly for `npx expo prebuild` & EAS Build
(eg: updated a module plugin).

---------

Co-authored-by: Expo Bot <34669131+expo-bot@users.noreply.github.com>
  • Loading branch information
EvanBacon and expo-bot committed Nov 8, 2023
1 parent 0b0a67b commit 4d37ee9
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/babel-preset-expo/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

### 🎉 New features

- Add `Platform.OS` shaking without needing to enable experimental ESM transforms. ([#25171](https://github.com/expo/expo/pull/25171) by [@EvanBacon](https://github.com/EvanBacon))
- Inline environment variables in production before the serializer to support source maps. ([#25239](https://github.com/expo/expo/pull/25239) by [@EvanBacon](https://github.com/EvanBacon))
- Support all options in top-level object and in `native` and `web` sub-objects. ([#25172](https://github.com/expo/expo/pull/25172) by [@EvanBacon](https://github.com/EvanBacon))
- Use the standard `@babel/preset-react` for all React transformations. ([#25125](https://github.com/expo/expo/pull/25125) by [@EvanBacon](https://github.com/EvanBacon))
Expand Down
14 changes: 14 additions & 0 deletions packages/babel-preset-expo/build/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ exports[`inlines environment variables 1`] = `
"
var foo = process.env.JEST_WORKER_ID;
process.env.ABC;
console.log(process.env.NODE_ENV);
console.log("production");
console.log("development");
"bar";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ process.env['other'];

expect(contents).toMatch('development');
expect(contents).toMatch('bar');
expect(contents).toMatch('process.env.NODE_ENV');
expect(contents).not.toMatch('process.env.NODE_ENV');
expect(contents).toMatch('process.env.JEST_WORKER_ID');
expect(contents).not.toMatch('EXPO_PUBLIC_NODE_ENV');
expect(contents).not.toMatch('EXPO_PUBLIC_FOO');
Expand Down
103 changes: 103 additions & 0 deletions packages/babel-preset-expo/src/__tests__/platform-shaking.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import * as babel from '@babel/core';

import preset from '..';

function getCaller(props: Record<string, string>): babel.TransformCaller {
return props as unknown as babel.TransformCaller;
}

const DEFAULT_OPTS = {
babelrc: false,
presets: [[preset]],
plugins: [
// Fold constants to emulate Metro
require('metro-transform-plugins/src/constant-folding-plugin.js'),
],
sourceMaps: true,
filename: 'unknown',
configFile: false,
compact: true,
comments: false,
retainLines: false,
};

function stripReactNativeImport(code: string) {
return code
.replace(
'var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _Platform=_interopRequireDefault(require("react-native-web/dist/exports/Platform"));',
''
)
.replace('var _reactNative=require("react-native");', '');
}

it(`removes Platform module usage on web`, () => {
const options = {
...DEFAULT_OPTS,
caller: getCaller({ name: 'metro', engine: 'hermes', platform: 'web' }),
};

const sourceCode = `
import { Platform } from 'react-native';
if (Platform.OS === 'ios') {
console.log('ios')
}
Platform.select({
ios: () => console.log('ios'),
web: () => console.log('web'),
android: () => console.log('android'),
})
`;

expect(stripReactNativeImport(babel.transform(sourceCode, options)!.code!)).toEqual(
`(function(){return console.log('web');});`
);
});

it(`removes Platform module usage on native`, () => {
const options = {
...DEFAULT_OPTS,
caller: getCaller({ name: 'metro', engine: 'hermes', platform: 'android' }),
};

expect(
babel.transform(
`Platform.select({ ios: () => console.log('ios'), web: () => console.log('web'), android: () => console.log('android'), })`,
options
)!.code
).toEqual(`(function(){return console.log('android');});`);

const sourceCode = `
import { Platform } from 'react-native';
if (Platform.OS === 'ios') {
console.log('ios')
}
Platform.select({
ios: () => console.log('ios'),
web: () => console.log('web'),
android: () => console.log('android'),
})
`;

expect(stripReactNativeImport(babel.transform(sourceCode, options)!.code!)).toEqual(
`(function(){return console.log('android');});`
);
});

it(`removes __DEV__ usage`, () => {
const options = {
...DEFAULT_OPTS,
caller: getCaller({ name: 'metro', engine: 'hermes', platform: 'android' }),
};

const sourceCode = `
if (__DEV__) {
require('./foobar')
}
`;

expect(babel.transform(sourceCode, options)!.code!).toEqual(``);
});
15 changes: 15 additions & 0 deletions packages/babel-preset-expo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,21 @@ function babelPresetExpo(api: ConfigAPI, options: BabelPresetExpoOptions = {}):
extraPlugins.push(require('@babel/plugin-transform-parameters'));
}

if (!isDev && hasModule('metro-transform-plugins')) {
// Metro applies this plugin too but it does it after the imports have been transformed which breaks
// the plugin. Here, we'll apply it before the commonjs transform, in production, to ensure `Platform.OS`
// is replaced with a string literal and `__DEV__` is converted to a boolean.
// Applying early also means that web can be transformed before the `react-native-web` transform mutates the import.
extraPlugins.push([
require('metro-transform-plugins/src/inline-plugin.js'),
{
dev: isDev,
inlinePlatform: true,
platform,
},
]);
}

if (platformOptions.useTransformReactJSXExperimental != null) {
throw new Error(
`babel-preset-expo: The option 'useTransformReactJSXExperimental' has been removed in favor of { jsxRuntime: 'classic' }.`
Expand Down

0 comments on commit 4d37ee9

Please sign in to comment.