babel-preset-expo 9.8.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # babel-preset-expo
2
2
 
3
- This preset extends the default React Native preset (`metro-react-native-babel-preset`) and adds support for decorators, tree-shaking web packages, and loading font icons with optional native dependencies if they're installed.
3
+ This preset extends the default React Native preset (`@react-native/babel-preset`) and adds support for decorators, tree-shaking web packages, and loading font icons with optional native dependencies if they're installed.
4
4
 
5
- You can use this preset in any React Native project as a drop-in replacement for `metro-react-native-babel-preset`. If your project isn't using native font loading or web support then this preset will only add support for decorators with `@babel/plugin-proposal-decorators` - this is mostly used for supporting legacy community libraries.
5
+ You can use this preset in any React Native project as a drop-in replacement for `@react-native/babel-preset`. If your project isn't using native font loading or web support then this preset will only add support for decorators with `@babel/plugin-proposal-decorators` - this is mostly used for supporting legacy community libraries.
6
6
 
7
7
  If you start your **web** project with `@expo/webpack-config` or `npx expo start` and your project doesn't contain a `babel.config.js` or a `.babelrc` then it will default to using `babel-preset-expo` for loading.
8
8
 
@@ -62,7 +62,7 @@ If the `bundler` is not defined, it will default to checking if a `babel-loader`
62
62
  ];
63
63
  ```
64
64
 
65
- This property is passed down to [`@babel/plugin-transform-react-jsx`](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx). This flag does nothing when `native.useTransformReactJSXExperimental` is set to `true` because `@babel/plugin-transform-react-jsx` is omitted.
65
+ This property is passed down to [`@babel/plugin-transform-react-jsx`](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx). This flag does nothing when `useTransformReactJSXExperimental` is set to `true` because `@babel/plugin-transform-react-jsx` is omitted.
66
66
 
67
67
  ### [`jsxImportSource`](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#importsource)
68
68
 
@@ -92,14 +92,10 @@ This can improve the initial load time of your app because evaluating dependenci
92
92
 
93
93
  The value of `lazyImports` has a few possible effects:
94
94
 
95
- - `null` - [metro-react-native-babel-preset](https://github.com/facebook/metro/tree/master/packages/metro-react-native-babel-preset) will handle it. (Learn more about it here: https://github.com/facebook/metro/commit/23e3503dde5f914f3e642ef214f508d0a699851d)
96
-
95
+ - `null` - [@react-native/babel-preset](https://github.com/facebook/react-native/tree/main/packages/react-native-babel-preset) will handle it. (Learn more about it here: https://github.com/facebook/metro/commit/23e3503dde5f914f3e642ef214f508d0a699851d)
97
96
  - `false` - No lazy initialization of any imported module.
98
-
99
97
  - `true` - Lazy-init all imported modules except local imports (e.g., `./foo`), certain Expo packages that have side effects, and the two cases mentioned [here](https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs#lazy).
100
-
101
98
  - `Array<string>` - [babel-plugin-transform-modules-commonjs](https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs#lazy) will handle it.
102
-
103
99
  - `(string) => boolean` - [babel-plugin-transform-modules-commonjs](https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs#lazy) will handle it.
104
100
 
105
101
  If you choose to do this, you can also access the list of Expo packages that have side effects by using `const lazyImportsBlacklist = require('babel-preset-expo/lazy-imports-blacklist');` which returns a `Set`.
@@ -115,19 +111,61 @@ The value of `lazyImports` has a few possible effects:
115
111
  ],
116
112
  ```
117
113
 
118
- ### `web.disableImportExportTransform`
114
+ ### `disableImportExportTransform`
119
115
 
120
- Enabling this option will allow your project to run with older JavaScript syntax (i.e. `module.exports`). This option will break tree shaking and increase your bundle size, but will eliminate the following error when `module.exports` is used:
116
+ Pass `true` to disable the transform that converts import/export to `module.exports`. Avoid setting this property directly. If you're using Metro, set `experimentalImportSupport: true` instead to ensure the entire pipeline is configured correctly.
121
117
 
122
- > `TypeError: Cannot assign to read only property 'exports' of object '#<Object>'`
118
+ ```js
119
+ // metro.config.js
123
120
 
124
- **default:** `false` when using Webpack. `true` otherwise.
121
+ config.transformer.getTransformOptions = async () => ({
122
+ transform: {
123
+ // Setting this to `true` will automatically toggle `disableImportExportTransform` in `babel-preset-expo`.
124
+ experimentalImportSupport: true,
125
+ },
126
+ });
127
+ ```
128
+
129
+ If `undefined` (default), this will be set automatically via `caller.supportsStaticESM` which is set by the bundler.
125
130
 
126
131
  ```js
127
132
  [
128
133
  'babel-preset-expo',
129
134
  {
130
- web: { disableImportExportTransform: true }
135
+ disableImportExportTransform: true
131
136
  }
132
137
  ],
133
138
  ```
139
+
140
+ ### `unstable_transformProfile`
141
+
142
+ Changes the engine preset in `@react-native/babel-preset` based on the JavaScript engine that is being targeted. In Expo SDK 50 and greater, this is automatically set based on the [`jsEngine`](https://docs.expo.dev/versions/latest/config/app/#jsengine) option in your `app.json`.
143
+
144
+ ### `enableBabelRuntime`
145
+
146
+ Passed to `@react-native/babel-preset`.
147
+
148
+ ### `disableFlowStripTypesTransform`
149
+
150
+ Passed to `@react-native/babel-preset`.
151
+
152
+ ## Platform-specific options
153
+
154
+ All options can be passed in the platform-specific objects `native` and `web` to provide different settings on different platforms. For example, if you'd like to only apply `disableImportExportTransform` on web, use the following:
155
+
156
+ ```js
157
+ [
158
+ 'babel-preset-expo',
159
+ {
160
+ // Default value:
161
+ disableImportExportTransform: false,
162
+
163
+ web: {
164
+ // Web-specific value:
165
+ disableImportExportTransform: true,
166
+ },
167
+ },
168
+ ];
169
+ ```
170
+
171
+ Platform-specific options have higher priority over top-level options.
package/build/common.d.ts CHANGED
@@ -3,3 +3,12 @@ export declare function hasModule(name: string): boolean;
3
3
  export declare function getBundler(caller: any): any;
4
4
  export declare function getPlatform(caller: any): any;
5
5
  export declare function getPossibleProjectRoot(caller: any): any;
6
+ export declare function getIsDev(caller: any): any;
7
+ export declare function getIsFastRefreshEnabled(caller: any): any;
8
+ export declare function getIsProd(caller: any): boolean;
9
+ export declare function getIsNodeModule(caller: any): boolean;
10
+ export declare function getBaseUrl(caller: any): string;
11
+ export declare function getIsServer(caller: any): any;
12
+ export declare function getExpoRouterAbsoluteAppRoot(caller: any): string;
13
+ export declare function getInlineEnvVarsEnabled(caller: any): boolean;
14
+ export declare function getAsyncRoutes(caller: any): boolean;
package/build/common.js CHANGED
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPossibleProjectRoot = exports.getPlatform = exports.getBundler = exports.hasModule = void 0;
6
+ exports.getAsyncRoutes = exports.getInlineEnvVarsEnabled = exports.getExpoRouterAbsoluteAppRoot = exports.getIsServer = exports.getBaseUrl = exports.getIsNodeModule = exports.getIsProd = exports.getIsFastRefreshEnabled = exports.getIsDev = exports.getPossibleProjectRoot = exports.getPlatform = exports.getBundler = exports.hasModule = void 0;
7
+ const path_1 = __importDefault(require("path"));
4
8
  function hasModule(name) {
5
9
  try {
6
10
  return !!require.resolve(name);
@@ -52,3 +56,68 @@ function getPossibleProjectRoot(caller) {
52
56
  return process.env.EXPO_PROJECT_ROOT;
53
57
  }
54
58
  exports.getPossibleProjectRoot = getPossibleProjectRoot;
59
+ function getIsDev(caller) {
60
+ if (caller?.isDev != null)
61
+ return caller.isDev;
62
+ // https://babeljs.io/docs/options#envname
63
+ return process.env.BABEL_ENV === 'development' || process.env.NODE_ENV === 'development';
64
+ }
65
+ exports.getIsDev = getIsDev;
66
+ function getIsFastRefreshEnabled(caller) {
67
+ if (!caller)
68
+ return false;
69
+ return caller.isHMREnabled && !caller.isServer && !caller.isNodeModule && getIsDev(caller);
70
+ }
71
+ exports.getIsFastRefreshEnabled = getIsFastRefreshEnabled;
72
+ function getIsProd(caller) {
73
+ if (caller?.isDev != null)
74
+ return caller.isDev === false;
75
+ // https://babeljs.io/docs/options#envname
76
+ return process.env.BABEL_ENV === 'production' || process.env.NODE_ENV === 'production';
77
+ }
78
+ exports.getIsProd = getIsProd;
79
+ function getIsNodeModule(caller) {
80
+ return caller?.isNodeModule ?? false;
81
+ }
82
+ exports.getIsNodeModule = getIsNodeModule;
83
+ function getBaseUrl(caller) {
84
+ return caller?.baseUrl ?? '';
85
+ }
86
+ exports.getBaseUrl = getBaseUrl;
87
+ function getIsServer(caller) {
88
+ return caller?.isServer ?? false;
89
+ }
90
+ exports.getIsServer = getIsServer;
91
+ function getExpoRouterAbsoluteAppRoot(caller) {
92
+ const rootModuleId = caller?.routerRoot ?? './app';
93
+ if (path_1.default.isAbsolute(rootModuleId)) {
94
+ return rootModuleId;
95
+ }
96
+ const projectRoot = getPossibleProjectRoot(caller) || '/';
97
+ return path_1.default.join(projectRoot, rootModuleId);
98
+ }
99
+ exports.getExpoRouterAbsoluteAppRoot = getExpoRouterAbsoluteAppRoot;
100
+ function getInlineEnvVarsEnabled(caller) {
101
+ const isWebpack = getBundler(caller) === 'webpack';
102
+ const isDev = getIsDev(caller);
103
+ const isServer = getIsServer(caller);
104
+ const isNodeModule = getIsNodeModule(caller);
105
+ const preserveEnvVars = caller?.preserveEnvVars;
106
+ // Development env vars are added in the serializer to avoid caching issues in development.
107
+ // Servers have env vars left as-is to read from the environment.
108
+ return !isNodeModule && !isWebpack && !isDev && !isServer && !preserveEnvVars;
109
+ }
110
+ exports.getInlineEnvVarsEnabled = getInlineEnvVarsEnabled;
111
+ function getAsyncRoutes(caller) {
112
+ const isServer = getIsServer(caller);
113
+ if (isServer) {
114
+ return false;
115
+ }
116
+ const isProd = getIsProd(caller);
117
+ const platform = getPlatform(caller);
118
+ if (platform !== 'web' && isProd) {
119
+ return false;
120
+ }
121
+ return caller?.asyncRoutes ?? false;
122
+ }
123
+ exports.getAsyncRoutes = getAsyncRoutes;
@@ -6,9 +6,7 @@ import { ConfigAPI, types } from '@babel/core';
6
6
  * EXPO_PUBLIC_USE_STATIC
7
7
  * EXPO_ROUTER_ABS_APP_ROOT
8
8
  * EXPO_ROUTER_APP_ROOT
9
- * EXPO_ROUTER_IMPORT_MODE_IOS
10
- * EXPO_ROUTER_IMPORT_MODE_ANDROID
11
- * EXPO_ROUTER_IMPORT_MODE_WEB
9
+ * EXPO_ROUTER_IMPORT_MODE
12
10
  */
13
11
  export declare function expoRouterBabelPlugin(api: ConfigAPI & {
14
12
  types: typeof types;
@@ -4,92 +4,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.expoRouterBabelPlugin = void 0;
7
- const config_1 = require("expo/config");
8
- const fs_1 = __importDefault(require("fs"));
7
+ const core_1 = require("@babel/core");
9
8
  const path_1 = __importDefault(require("path"));
10
9
  const resolve_from_1 = __importDefault(require("resolve-from"));
11
10
  const common_1 = require("./common");
12
11
  const debug = require('debug')('expo:babel:router');
13
- let config;
14
- function getConfigMemo(projectRoot) {
15
- if (!config || process.env._EXPO_INTERNAL_TESTING) {
16
- config = (0, config_1.getConfig)(projectRoot);
17
- }
18
- return config;
19
- }
20
- function getExpoRouterImportMode(projectRoot, platform) {
21
- const envVar = 'EXPO_ROUTER_IMPORT_MODE_' + platform.toUpperCase();
22
- if (process.env[envVar]) {
23
- return process.env[envVar];
24
- }
25
- const env = process.env.NODE_ENV || process.env.BABEL_ENV;
26
- const { exp } = getConfigMemo(projectRoot);
27
- let asyncRoutesSetting;
28
- if (exp.extra?.router?.asyncRoutes) {
29
- const asyncRoutes = exp.extra?.router?.asyncRoutes;
30
- if (typeof asyncRoutes === 'string') {
31
- asyncRoutesSetting = asyncRoutes;
32
- }
33
- else if (typeof asyncRoutes === 'object') {
34
- asyncRoutesSetting = asyncRoutes[platform] ?? asyncRoutes.default;
35
- }
36
- }
37
- let mode = [env, true].includes(asyncRoutesSetting) ? 'lazy' : 'sync';
38
- // TODO: Production bundle splitting
39
- if (env === 'production' && mode === 'lazy') {
40
- throw new Error('Async routes are not supported in production yet. Set the `expo-router` Config Plugin prop `asyncRoutes` to `development`, `false`, or `undefined`.');
41
- }
42
- // NOTE: This is a temporary workaround for static rendering on web.
43
- if (platform === 'web' && (exp.web || {}).output === 'static') {
44
- mode = 'sync';
45
- }
46
- // Development
47
- debug('Router import mode', mode);
48
- process.env[envVar] = mode;
49
- return mode;
50
- }
51
- function directoryExistsSync(file) {
52
- return fs_1.default.statSync(file, { throwIfNoEntry: false })?.isDirectory() ?? false;
53
- }
54
- function getRouterDirectory(projectRoot) {
55
- // more specific directories first
56
- if (directoryExistsSync(path_1.default.join(projectRoot, 'src/app'))) {
57
- // Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));
58
- return './src/app';
59
- }
60
- // Log.debug('Using app as the root directory for Expo Router.');
61
- return './app';
62
- }
63
- function getExpoRouterAppRoot(projectRoot) {
64
- // Bump to v2 to prevent the CLI from setting the variable anymore.
65
- // TODO: Bump to v3 to revert back to the CLI setting the variable again, but with custom value
66
- // support.
67
- if (process.env.EXPO_ROUTER_APP_ROOT_2) {
68
- return process.env.EXPO_ROUTER_APP_ROOT_2;
69
- }
12
+ function getExpoRouterAppRoot(projectRoot, appFolder) {
13
+ // TODO: We should have cache invalidation if the expo-router/entry file location changes.
70
14
  const routerEntry = (0, resolve_from_1.default)(projectRoot, 'expo-router/entry');
71
- // It doesn't matter if the app folder exists.
72
- const appFolder = getExpoRouterAbsoluteAppRoot(projectRoot);
73
15
  const appRoot = path_1.default.relative(path_1.default.dirname(routerEntry), appFolder);
74
16
  debug('routerEntry', routerEntry, appFolder, appRoot);
75
- process.env.EXPO_ROUTER_APP_ROOT_2 = appRoot;
76
17
  return appRoot;
77
18
  }
78
- function getExpoRouterAbsoluteAppRoot(projectRoot) {
79
- if (process.env.EXPO_ROUTER_ABS_APP_ROOT) {
80
- return process.env.EXPO_ROUTER_ABS_APP_ROOT;
81
- }
82
- const { exp } = getConfigMemo(projectRoot);
83
- const customSrc = exp.extra?.router?.unstable_src || getRouterDirectory(projectRoot);
84
- const isAbsolute = customSrc.startsWith('/');
85
- // It doesn't matter if the app folder exists.
86
- const appFolder = isAbsolute ? customSrc : path_1.default.join(projectRoot, customSrc);
87
- const appRoot = appFolder;
88
- debug('absolute router entry', appFolder, appRoot);
89
- process.env.EXPO_ROUTER_ABS_APP_ROOT = appFolder;
90
- return appRoot;
91
- }
92
- // TODO: Strip the function `generateStaticParams` when bundling for node.js environments.
93
19
  /**
94
20
  * Inlines environment variables to configure the process:
95
21
  *
@@ -97,80 +23,57 @@ function getExpoRouterAbsoluteAppRoot(projectRoot) {
97
23
  * EXPO_PUBLIC_USE_STATIC
98
24
  * EXPO_ROUTER_ABS_APP_ROOT
99
25
  * EXPO_ROUTER_APP_ROOT
100
- * EXPO_ROUTER_IMPORT_MODE_IOS
101
- * EXPO_ROUTER_IMPORT_MODE_ANDROID
102
- * EXPO_ROUTER_IMPORT_MODE_WEB
26
+ * EXPO_ROUTER_IMPORT_MODE
103
27
  */
104
28
  function expoRouterBabelPlugin(api) {
105
29
  const { types: t } = api;
106
30
  const platform = api.caller(common_1.getPlatform);
107
31
  const possibleProjectRoot = api.caller(common_1.getPossibleProjectRoot);
32
+ const asyncRoutes = api.caller(common_1.getAsyncRoutes);
33
+ const routerAbsoluteRoot = api.caller(common_1.getExpoRouterAbsoluteAppRoot);
34
+ function isFirstInAssign(path) {
35
+ return core_1.types.isAssignmentExpression(path.parent) && path.parent.left === path.node;
36
+ }
108
37
  return {
109
38
  name: 'expo-router',
110
39
  visitor: {
111
- // Convert `process.env.EXPO_ROUTER_APP_ROOT` to a string literal
112
40
  MemberExpression(path, state) {
113
- if (!t.isIdentifier(path.node.object, { name: 'process' }) ||
114
- !t.isIdentifier(path.node.property, { name: 'env' })) {
115
- return;
116
- }
117
- const parent = path.parentPath;
118
- if (!t.isMemberExpression(parent.node)) {
119
- return;
120
- }
121
41
  const projectRoot = possibleProjectRoot || state.file.opts.root || '';
122
- // Used for log box and stuff
123
- if (t.isIdentifier(parent.node.property, {
124
- name: 'EXPO_PROJECT_ROOT',
125
- }) &&
126
- !parent.parentPath.isAssignmentExpression()) {
127
- parent.replaceWith(t.stringLiteral(projectRoot));
128
- }
129
- else if (
130
- // Enable static rendering
131
- // TODO: Use a serializer or something to ensure this changes without
132
- // needing to clear the cache.
133
- t.isIdentifier(parent.node.property, {
134
- name: 'EXPO_PUBLIC_USE_STATIC',
135
- }) &&
136
- !parent.parentPath.isAssignmentExpression()) {
137
- if (platform === 'web') {
138
- const isStatic = process.env.EXPO_PUBLIC_USE_STATIC === 'true' ||
139
- process.env.EXPO_PUBLIC_USE_STATIC === '1';
140
- parent.replaceWith(t.booleanLiteral(isStatic));
141
- }
142
- else {
143
- parent.replaceWith(t.booleanLiteral(false));
42
+ if (path.get('object').matchesPattern('process.env')) {
43
+ const key = path.toComputedKey();
44
+ if (t.isStringLiteral(key) && !isFirstInAssign(path)) {
45
+ // Used for log box on web.
46
+ if (key.value.startsWith('EXPO_PROJECT_ROOT')) {
47
+ path.replaceWith(t.stringLiteral(projectRoot));
48
+ }
49
+ else if (
50
+ // TODO: Add cache invalidation.
51
+ key.value.startsWith('EXPO_PUBLIC_USE_STATIC')) {
52
+ if (platform === 'web') {
53
+ const isStatic = process.env.EXPO_PUBLIC_USE_STATIC === 'true' ||
54
+ process.env.EXPO_PUBLIC_USE_STATIC === '1';
55
+ path.replaceWith(t.booleanLiteral(isStatic));
56
+ }
57
+ else {
58
+ path.replaceWith(t.booleanLiteral(false));
59
+ }
60
+ }
61
+ else if (key.value.startsWith('EXPO_ROUTER_IMPORT_MODE')) {
62
+ path.replaceWith(t.stringLiteral(asyncRoutes ? 'lazy' : 'sync'));
63
+ }
64
+ if (
65
+ // Skip loading the app root in tests.
66
+ // This is handled by the testing-library utils
67
+ process.env.NODE_ENV !== 'test') {
68
+ if (key.value.startsWith('EXPO_ROUTER_ABS_APP_ROOT')) {
69
+ path.replaceWith(t.stringLiteral(routerAbsoluteRoot));
70
+ }
71
+ else if (key.value.startsWith('EXPO_ROUTER_APP_ROOT')) {
72
+ path.replaceWith(t.stringLiteral(getExpoRouterAppRoot(possibleProjectRoot, routerAbsoluteRoot)));
73
+ }
74
+ }
144
75
  }
145
76
  }
146
- else if (process.env.NODE_ENV !== 'test' &&
147
- t.isIdentifier(parent.node.property, {
148
- name: 'EXPO_ROUTER_ABS_APP_ROOT',
149
- }) &&
150
- !parent.parentPath.isAssignmentExpression()) {
151
- parent.replaceWith(t.stringLiteral(getExpoRouterAbsoluteAppRoot(projectRoot)));
152
- }
153
- else if (
154
- // Skip loading the app root in tests.
155
- // This is handled by the testing-library utils
156
- process.env.NODE_ENV !== 'test' &&
157
- t.isIdentifier(parent.node.property, {
158
- name: 'EXPO_ROUTER_APP_ROOT',
159
- }) &&
160
- !parent.parentPath.isAssignmentExpression()) {
161
- parent.replaceWith(
162
- // This is defined in Expo CLI when using Metro. It points to the relative path for the project app directory.
163
- t.stringLiteral(getExpoRouterAppRoot(projectRoot)));
164
- }
165
- else if (
166
- // Expose the app route import mode.
167
- platform &&
168
- t.isIdentifier(parent.node.property, {
169
- name: 'EXPO_ROUTER_IMPORT_MODE_' + platform.toUpperCase(),
170
- }) &&
171
- !parent.parentPath.isAssignmentExpression()) {
172
- parent.replaceWith(t.stringLiteral(getExpoRouterImportMode(projectRoot, platform)));
173
- }
174
77
  },
175
78
  },
176
79
  };
package/build/index.d.ts CHANGED
@@ -1,18 +1,23 @@
1
1
  import { ConfigAPI, TransformOptions } from '@babel/core';
2
2
  type BabelPresetExpoPlatformOptions = {
3
+ /** Enable or disable adding the Reanimated plugin by default. @default `true` */
4
+ reanimated?: boolean;
5
+ /** @deprecated Set `jsxRuntime: 'classic'` to disable automatic JSX handling. */
3
6
  useTransformReactJSXExperimental?: boolean;
7
+ /** Change the policy for handling JSX in a file. Passed to `plugin-transform-react-jsx`. @default `'automatic'` */
8
+ jsxRuntime?: 'classic' | 'automatic';
9
+ /** Change the source module ID to use when importing an automatic JSX import. Only applied when `jsxRuntime` is `'automatic'` (default). Passed to `plugin-transform-react-jsx`. @default `'react'` */
10
+ jsxImportSource?: string;
11
+ lazyImports?: boolean;
4
12
  disableImportExportTransform?: boolean;
5
- withDevTools?: boolean;
6
13
  disableFlowStripTypesTransform?: boolean;
7
14
  enableBabelRuntime?: boolean;
8
15
  unstable_transformProfile?: 'default' | 'hermes-stable' | 'hermes-canary';
9
16
  };
10
- export type BabelPresetExpoOptions = {
11
- lazyImports?: boolean;
12
- reanimated?: boolean;
13
- jsxRuntime?: 'classic' | 'automatic';
14
- jsxImportSource?: string;
17
+ export type BabelPresetExpoOptions = BabelPresetExpoPlatformOptions & {
18
+ /** Web-specific settings. */
15
19
  web?: BabelPresetExpoPlatformOptions;
20
+ /** Native-specific settings. */
16
21
  native?: BabelPresetExpoPlatformOptions;
17
22
  };
18
23
  declare function babelPresetExpo(api: ConfigAPI, options?: BabelPresetExpoOptions): TransformOptions;
package/build/index.js CHANGED
@@ -3,37 +3,53 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const common_1 = require("./common");
4
4
  const expo_inline_manifest_plugin_1 = require("./expo-inline-manifest-plugin");
5
5
  const expo_router_plugin_1 = require("./expo-router-plugin");
6
+ const inline_env_vars_1 = require("./inline-env-vars");
6
7
  const lazyImports_1 = require("./lazyImports");
8
+ function getOptions(options, platform) {
9
+ const tag = platform === 'web' ? 'web' : 'native';
10
+ return {
11
+ ...options,
12
+ ...options[tag],
13
+ };
14
+ }
7
15
  function babelPresetExpo(api, options = {}) {
8
- const { web = {}, native = {}, reanimated } = options;
9
16
  const bundler = api.caller(common_1.getBundler);
10
17
  const isWebpack = bundler === 'webpack';
11
18
  let platform = api.caller((caller) => caller?.platform);
12
19
  const engine = api.caller((caller) => caller?.engine) ?? 'default';
20
+ const isDev = api.caller(common_1.getIsDev);
21
+ const isFastRefreshEnabled = api.caller(common_1.getIsFastRefreshEnabled);
22
+ const baseUrl = api.caller(common_1.getBaseUrl);
23
+ const supportsStaticESM = api.caller((caller) => caller?.supportsStaticESM);
24
+ // Unlike `isDev`, this will be `true` when the bundler is explicitly set to `production`,
25
+ // i.e. `false` when testing, development, or used with a bundler that doesn't specify the correct inputs.
26
+ const isProduction = api.caller(common_1.getIsProd);
27
+ const inlineEnvironmentVariables = api.caller(common_1.getInlineEnvVarsEnabled);
13
28
  // If the `platform` prop is not defined then this must be a custom config that isn't
14
29
  // defining a platform in the babel-loader. Currently this may happen with Next.js + Expo web.
15
30
  if (!platform && isWebpack) {
16
31
  platform = 'web';
17
32
  }
18
- const platformOptions = platform === 'web'
19
- ? {
33
+ const platformOptions = getOptions(options, platform);
34
+ if (platformOptions.disableImportExportTransform == null) {
35
+ if (platform === 'web') {
20
36
  // Only disable import/export transform when Webpack is used because
21
37
  // Metro does not support tree-shaking.
22
- disableImportExportTransform: isWebpack,
23
- unstable_transformProfile: engine === 'hermes' ? 'hermes-stable' : 'default',
24
- ...web,
38
+ platformOptions.disableImportExportTransform = supportsStaticESM ?? isWebpack;
39
+ }
40
+ else {
41
+ platformOptions.disableImportExportTransform = supportsStaticESM ?? false;
25
42
  }
26
- : {
27
- disableImportExportTransform: false,
28
- unstable_transformProfile: engine === 'hermes' ? 'hermes-stable' : 'default',
29
- ...native,
30
- };
43
+ }
44
+ if (platformOptions.unstable_transformProfile == null) {
45
+ platformOptions.unstable_transformProfile = engine === 'hermes' ? 'hermes-stable' : 'default';
46
+ }
31
47
  // Note that if `options.lazyImports` is not set (i.e., `null` or `undefined`),
32
- // `metro-react-native-babel-preset` will handle it.
33
- const lazyImportsOption = options?.lazyImports;
48
+ // `@react-native/babel-preset` will handle it.
49
+ const lazyImportsOption = platformOptions?.lazyImports;
34
50
  const extraPlugins = [];
35
51
  if (engine !== 'hermes') {
36
- // `metro-react-native-babel-preset` configures this plugin with `{ loose: true }`, which breaks all
52
+ // `@react-native/babel-preset` configures this plugin with `{ loose: true }`, which breaks all
37
53
  // getters and setters in spread objects. We need to add this plugin ourself without that option.
38
54
  // @see https://github.com/expo/expo/pull/11960#issuecomment-887796455
39
55
  extraPlugins.push([
@@ -41,30 +57,47 @@ function babelPresetExpo(api, options = {}) {
41
57
  { loose: false },
42
58
  ]);
43
59
  }
44
- // Set true to disable `@babel/plugin-transform-react-jsx`
45
- // we override this logic outside of the metro preset so we can add support for
46
- // React 17 automatic JSX transformations.
47
- // If the logic for `useTransformReactJSXExperimental` ever changes in `metro-react-native-babel-preset`
48
- // then this block should be updated to reflect those changes.
49
- if (!platformOptions.useTransformReactJSXExperimental) {
60
+ else {
61
+ // This is added back on hermes to ensure the react-jsx-dev plugin (`@babel/preset-react`) works as expected when
62
+ // JSX is used in a function body. This is technically not required in production, but we
63
+ // should retain the same behavior since it's hard to debug the differences.
64
+ extraPlugins.push(require('@babel/plugin-transform-parameters'));
65
+ }
66
+ if (isProduction && (0, common_1.hasModule)('metro-transform-plugins')) {
67
+ // Metro applies this plugin too but it does it after the imports have been transformed which breaks
68
+ // the plugin. Here, we'll apply it before the commonjs transform, in production, to ensure `Platform.OS`
69
+ // is replaced with a string literal and `__DEV__` is converted to a boolean.
70
+ // Applying early also means that web can be transformed before the `react-native-web` transform mutates the import.
71
+ extraPlugins.push([
72
+ require('metro-transform-plugins/src/inline-plugin.js'),
73
+ {
74
+ dev: isDev,
75
+ inlinePlatform: true,
76
+ platform,
77
+ },
78
+ ]);
79
+ }
80
+ if (platformOptions.useTransformReactJSXExperimental != null) {
81
+ throw new Error(`babel-preset-expo: The option 'useTransformReactJSXExperimental' has been removed in favor of { jsxRuntime: 'classic' }.`);
82
+ }
83
+ // Allow jest tests to redefine the environment variables.
84
+ if (process.env.NODE_ENV !== 'test') {
50
85
  extraPlugins.push([
51
- require('@babel/plugin-transform-react-jsx'),
86
+ inline_env_vars_1.expoInlineTransformEnvVars,
52
87
  {
53
- // Defaults to `automatic`, pass in `classic` to disable auto JSX transformations.
54
- runtime: (options && options.jsxRuntime) || 'automatic',
55
- ...(options &&
56
- options.jsxRuntime !== 'classic' && {
57
- importSource: (options && options.jsxImportSource) || 'react',
58
- }),
88
+ // These values should not be prefixed with `EXPO_PUBLIC_`, so we don't
89
+ // squat user-defined environment variables.
90
+ EXPO_BASE_URL: baseUrl,
59
91
  },
60
92
  ]);
61
- // Purposefully not adding the deprecated packages:
62
- // `@babel/plugin-transform-react-jsx-self` and `@babel/plugin-transform-react-jsx-source`
63
- // back to the preset.
64
93
  }
65
- const aliasPlugin = getAliasPlugin();
66
- if (aliasPlugin) {
67
- extraPlugins.push(aliasPlugin);
94
+ // Only apply in non-server, for metro-only, in production environments, when the user hasn't disabled the feature.
95
+ // Webpack uses DefinePlugin for environment variables.
96
+ // Development uses an uncached serializer.
97
+ // Servers read from the environment.
98
+ // Users who disable the feature may be using a different babel plugin.
99
+ if (inlineEnvironmentVariables) {
100
+ extraPlugins.push(inline_env_vars_1.expoInlineEnvVars);
68
101
  }
69
102
  if (platform === 'web') {
70
103
  extraPlugins.push(require.resolve('babel-plugin-react-native-web'));
@@ -76,17 +109,24 @@ function babelPresetExpo(api, options = {}) {
76
109
  if ((0, common_1.hasModule)('expo-router')) {
77
110
  extraPlugins.push(expo_router_plugin_1.expoRouterBabelPlugin);
78
111
  }
112
+ if (isFastRefreshEnabled) {
113
+ extraPlugins.push([
114
+ require('react-refresh/babel'),
115
+ {
116
+ // We perform the env check to enable `isFastRefreshEnabled`.
117
+ skipEnvCheck: true,
118
+ },
119
+ ]);
120
+ }
79
121
  return {
80
122
  presets: [
81
123
  [
82
124
  // We use `require` here instead of directly using the package name because we want to
83
- // specifically use the `metro-react-native-babel-preset` installed by this package (ex:
125
+ // specifically use the `@react-native/babel-preset` installed by this package (ex:
84
126
  // `babel-preset-expo/node_modules/`). This way the preset will not change unintentionally.
85
127
  // Reference: https://github.com/expo/expo/pull/4685#discussion_r307143920
86
- require('metro-react-native-babel-preset'),
128
+ require('@react-native/babel-preset'),
87
129
  {
88
- // Defaults to undefined, set to something truthy to disable `@babel/plugin-transform-react-jsx-self` and `@babel/plugin-transform-react-jsx-source`.
89
- withDevTools: platformOptions.withDevTools,
90
130
  // Defaults to undefined, set to `true` to disable `@babel/plugin-transform-flow-strip-types`
91
131
  disableFlowStripTypesTransform: platformOptions.disableFlowStripTypesTransform,
92
132
  // Defaults to undefined, set to `false` to disable `@babel/plugin-transform-runtime`
@@ -101,6 +141,9 @@ function babelPresetExpo(api, options = {}) {
101
141
  // TransformError App.js: /path/to/App.js: Duplicate __self prop found. You are most likely using the deprecated transform-react-jsx-self Babel plugin.
102
142
  // Both __source and __self are automatically set when using the automatic jsxRuntime. Please remove transform-react-jsx-source and transform-react-jsx-self from your Babel config.
103
143
  useTransformReactJSXExperimental: true,
144
+ // This will never be used regardless because `useTransformReactJSXExperimental` is set to `true`.
145
+ // https://github.com/facebook/react-native/blob/a4a8695cec640e5cf12be36a0c871115fbce9c87/packages/react-native-babel-preset/src/configs/main.js#L151
146
+ withDevTools: false,
104
147
  disableImportExportTransform: platformOptions.disableImportExportTransform,
105
148
  lazyImportExportTransform: lazyImportsOption === true
106
149
  ? (importModuleSpecifier) => {
@@ -108,36 +151,47 @@ function babelPresetExpo(api, options = {}) {
108
151
  // behavior) or are in the blacklist.
109
152
  return !(importModuleSpecifier.includes('./') || lazyImports_1.lazyImports.has(importModuleSpecifier));
110
153
  }
111
- : // Pass the option directly to `metro-react-native-babel-preset`, which in turn
154
+ : // Pass the option directly to `@react-native/babel-preset`, which in turn
112
155
  // passes it to `babel-plugin-transform-modules-commonjs`
113
156
  lazyImportsOption,
114
157
  },
115
158
  ],
159
+ // React support with similar options to Metro.
160
+ // We override this logic outside of the metro preset so we can add support for
161
+ // React 17 automatic JSX transformations.
162
+ // The only known issue is the plugin `@babel/plugin-transform-react-display-name` will be run twice,
163
+ // once in the Metro plugin, and another time here.
164
+ [
165
+ require('@babel/preset-react'),
166
+ {
167
+ development: isDev,
168
+ // Defaults to `automatic`, pass in `classic` to disable auto JSX transformations.
169
+ runtime: platformOptions?.jsxRuntime || 'automatic',
170
+ ...(platformOptions &&
171
+ platformOptions.jsxRuntime !== 'classic' && {
172
+ importSource: (platformOptions && platformOptions.jsxImportSource) || 'react',
173
+ }),
174
+ // NOTE: Unexposed props:
175
+ // pragma?: string;
176
+ // pragmaFrag?: string;
177
+ // pure?: string;
178
+ // throwIfNamespace?: boolean;
179
+ // useBuiltIns?: boolean;
180
+ // useSpread?: boolean;
181
+ },
182
+ ],
116
183
  ],
117
184
  plugins: [
118
185
  ...extraPlugins,
119
186
  // TODO: Remove
120
187
  [require.resolve('@babel/plugin-proposal-decorators'), { legacy: true }],
121
- require.resolve('@babel/plugin-proposal-export-namespace-from'),
188
+ require.resolve('@babel/plugin-transform-export-namespace-from'),
122
189
  // Automatically add `react-native-reanimated/plugin` when the package is installed.
123
190
  // TODO: Move to be a customTransformOption.
124
191
  (0, common_1.hasModule)('react-native-reanimated') &&
125
- reanimated !== false && [require.resolve('react-native-reanimated/plugin')],
192
+ platformOptions.reanimated !== false && [require.resolve('react-native-reanimated/plugin')],
126
193
  ].filter(Boolean),
127
194
  };
128
195
  }
129
- function getAliasPlugin() {
130
- if (!(0, common_1.hasModule)('@expo/vector-icons')) {
131
- return null;
132
- }
133
- return [
134
- require.resolve('babel-plugin-module-resolver'),
135
- {
136
- alias: {
137
- 'react-native-vector-icons': '@expo/vector-icons',
138
- },
139
- },
140
- ];
141
- }
142
196
  exports.default = babelPresetExpo;
143
197
  module.exports = babelPresetExpo;
@@ -0,0 +1,13 @@
1
+ import { ConfigAPI, PluginObj, types } from '@babel/core';
2
+ export declare function expoInlineEnvVars(api: ConfigAPI & {
3
+ types: typeof types;
4
+ }): PluginObj;
5
+ /**
6
+ * Given a set of options like `{ EXPO_BASE_URL: '/' }`, inline the values into the bundle.
7
+ * This is used for build settings that are always available and not configurable at runtime.
8
+ *
9
+ * Webpack uses DefinePlugin for similar functionality.
10
+ */
11
+ export declare function expoInlineTransformEnvVars(api: ConfigAPI & {
12
+ types: typeof types;
13
+ }): PluginObj;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.expoInlineTransformEnvVars = exports.expoInlineEnvVars = void 0;
4
+ const debug = require('debug')('expo:babel:env-vars');
5
+ function expoInlineEnvVars(api) {
6
+ const { types: t } = api;
7
+ function isFirstInAssign(path) {
8
+ return t.isAssignmentExpression(path.parent) && path.parent.left === path.node;
9
+ }
10
+ return {
11
+ name: 'expo-inline-production-environment-variables',
12
+ visitor: {
13
+ MemberExpression(path, state) {
14
+ const filename = state.filename;
15
+ if (path.get('object').matchesPattern('process.env')) {
16
+ // @ts-expect-error: missing types
17
+ const key = path.toComputedKey();
18
+ if (t.isStringLiteral(key) &&
19
+ !isFirstInAssign(path) &&
20
+ key.value.startsWith('EXPO_PUBLIC_')) {
21
+ debug('Inlining environment variable in %s: %s', filename, key.value);
22
+ path.replaceWith(t.valueToNode(process.env[key.value]));
23
+ }
24
+ }
25
+ },
26
+ },
27
+ };
28
+ }
29
+ exports.expoInlineEnvVars = expoInlineEnvVars;
30
+ /**
31
+ * Given a set of options like `{ EXPO_BASE_URL: '/' }`, inline the values into the bundle.
32
+ * This is used for build settings that are always available and not configurable at runtime.
33
+ *
34
+ * Webpack uses DefinePlugin for similar functionality.
35
+ */
36
+ function expoInlineTransformEnvVars(api) {
37
+ const { types: t } = api;
38
+ function isFirstInAssign(path) {
39
+ return t.isAssignmentExpression(path.parent) && path.parent.left === path.node;
40
+ }
41
+ return {
42
+ name: 'expo-inline-transform-environment-variables',
43
+ visitor: {
44
+ MemberExpression(path, state) {
45
+ const options = state.opts;
46
+ if (path.get('object').matchesPattern('process.env')) {
47
+ // @ts-expect-error: missing types
48
+ const key = path.toComputedKey();
49
+ if (t.isStringLiteral(key) &&
50
+ !isFirstInAssign(path) &&
51
+ options[key.value] !== undefined) {
52
+ debug('Inlining transform setting in %s: %s', state.filename || '[unknown file]', key.value);
53
+ path.replaceWith(t.valueToNode(options[key.value]));
54
+ }
55
+ }
56
+ },
57
+ },
58
+ };
59
+ }
60
+ exports.expoInlineTransformEnvVars = expoInlineTransformEnvVars;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "babel-preset-expo",
3
- "version": "9.8.0",
3
+ "version": "10.0.0",
4
4
  "description": "The Babel preset for Expo projects",
5
5
  "main": "build/index.js",
6
6
  "files": [
@@ -42,17 +42,19 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@babel/plugin-proposal-decorators": "^7.12.9",
45
- "@babel/plugin-proposal-export-namespace-from": "^7.18.9",
46
45
  "@babel/plugin-proposal-object-rest-spread": "^7.12.13",
47
- "@babel/plugin-transform-react-jsx": "^7.12.17",
46
+ "@babel/plugin-transform-export-namespace-from": "^7.22.11",
48
47
  "@babel/preset-env": "^7.20.0",
49
- "babel-plugin-module-resolver": "^5.0.0",
48
+ "@babel/preset-react": "^7.22.15",
49
+ "@babel/plugin-transform-parameters": "^7.22.15",
50
+ "@react-native/babel-preset": "^0.73.18",
50
51
  "babel-plugin-react-native-web": "~0.18.10",
51
- "metro-react-native-babel-preset": "0.76.8"
52
+ "react-refresh": "0.14.0"
52
53
  },
53
54
  "devDependencies": {
54
55
  "@babel/core": "^7.20.0",
56
+ "expo-module-scripts": "^3.3.0",
55
57
  "jest": "^29.2.1"
56
58
  },
57
- "gitHead": "ee7897097f5f946ad7fcb94447eed789b984dd02"
59
+ "gitHead": "6aca7ce098ddc667776a3d7cf612adbb985e264a"
58
60
  }