Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(babel): fix unused platform code removal #25171

Merged
merged 8 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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')) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why should this not run in development, too?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't do any minification in development to keep things fast, might change in the future but right now it doesn't provide much benefit.

// 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'),
EvanBacon marked this conversation as resolved.
Show resolved Hide resolved
{
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