babel-plugin-react-native-direct-imports 1.0.2 → 1.1.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.
Files changed (3) hide show
  1. package/README.md +27 -46
  2. package/index.js +291 -28
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -4,57 +4,47 @@
4
4
  [![npm downloads](https://badgen.net/npm/dm/babel-plugin-react-native-direct-imports)](https://www.npmtrends.com/babel-plugin-react-native-direct-imports)
5
5
  [![license](https://badgen.net/npm/license/babel-plugin-react-native-direct-imports)](https://www.npmjs.com/package/babel-plugin-react-native-direct-imports)
6
6
 
7
- Babel plugin that rewrites named imports from `react-native` into direct imports of the underlying modules, so Metro doesn't have to load the whole `react-native` barrel file.
7
+ Babel plugin that replaces `react-native` imports with direct requires of the underlying modules, so only what you use ends up in the bundle.
8
8
 
9
9
  ```js
10
10
  import { View, AppRegistry, Systrace } from 'react-native';
11
11
 
12
12
  // ↓ becomes
13
13
 
14
- import View from 'react-native/Libraries/Components/View/View';
15
- import { AppRegistry } from 'react-native/Libraries/ReactNative/AppRegistry';
16
- import * as Systrace from 'react-native/Libraries/Performance/Systrace';
14
+ const View = require('react-native/Libraries/Components/View/View').default;
15
+ const AppRegistry = require('react-native/Libraries/ReactNative/AppRegistry').AppRegistry;
16
+ const Systrace = require('react-native/Libraries/Performance/Systrace');
17
17
  ```
18
18
 
19
19
  ## Why
20
20
 
21
- React Native's entry file (`react-native/index.js`) is a CommonJS barrel: one `module.exports` object with a lazy `require()` getter for every public API. The getters only delay running a module. Every module they reference still ends up in your bundle.
21
+ `react-native/index.js` is a CommonJS barrel with a lazy `require()` getter for every public API. Bundlers can't tree-shake it, so a single `import { View } from 'react-native'` pulls in all of React Native (`VirtualView`, `PushNotificationIOS`, ...).
22
22
 
23
- Bundlers can't tree-shake CommonJS getters. Metro doesn't tree-shake at all, and even [Re.Pack](https://re-pack.dev) with tree-shaking enabled can't remove them. So a single `import { View } from 'react-native'` pulls in all of React Native's public API, including modules your app probably never uses, like `VirtualView`, `UTFSequence` or `PushNotificationIOS`.
23
+ Bundle with only `import { ReactNativeVersion } from 'react-native'`, before and after:
24
24
 
25
- This plugin skips the barrel and imports each module directly, so only the modules you actually import end up in the bundle.
25
+ ![Bundle before and after the plugin](./assets/before-after.png)
26
26
 
27
- For example, here is a bundle that only does `import { ReactNativeVersion } from 'react-native'`, before and after:
27
+ ### Why `require()` and not `import`?
28
28
 
29
- ![Bundle before and after the plugin](./assets/before-after.png)
29
+ React Native's modules are CommonJS. If the plugin emitted `import View from '...'`, Babel's CommonJS transform would wrap every one in `_interopRequireDefault()` / `_interopRequireWildcard()` and add those helpers to each file. A plain `require(...).default` gives the same value without the extra code.
30
30
 
31
31
  ## Install
32
32
 
33
33
  ```bash
34
34
  npm install --save-dev babel-plugin-react-native-direct-imports
35
- # or
36
- yarn add -D babel-plugin-react-native-direct-imports
37
35
  ```
38
36
 
39
37
  ## Usage
40
38
 
41
- Add the plugin to your `babel.config.js`:
42
-
43
39
  ```js
44
- const isTest = process.env.NODE_ENV === 'test';
45
-
40
+ // babel.config.js
46
41
  module.exports = {
47
42
  presets: [
48
- [
49
- 'module:@react-native/babel-preset',
50
- {
51
- disableDeepImportWarnings: true, // <-- add this, the plugin generates deep imports on purpose
52
- },
53
- ],
43
+ // the plugin generates deep imports on purpose
44
+ ['module:@react-native/babel-preset', { disableDeepImportWarnings: true }],
54
45
  ],
55
46
  plugins: [
56
- // Skip the plugin in test environments
57
- !isTest && [
47
+ process.env.NODE_ENV !== 'test' && [
58
48
  'react-native-direct-imports',
59
49
  { reactNativeVersion: require('react-native/package.json').version },
60
50
  ],
@@ -62,39 +52,30 @@ module.exports = {
62
52
  };
63
53
  ```
64
54
 
65
- Then clear the Metro cache once:
55
+ Then reset the Metro cache once (`npx react-native start --reset-cache` or `npx expo start --clear`).
66
56
 
67
- ```bash
68
- npx react-native start --reset-cache
69
- # or, with Expo
70
- npx expo start --clear
71
- ```
57
+ `reactNativeVersion` picks the map from [`maps/`](maps) (default: the latest). Every stable release from `0.70.0` has one. The version must match exactly, otherwise the build fails, so update the plugin after upgrading React Native.
72
58
 
73
- ### Options
59
+ `silenceBatchedUpdatesWarning` (default: `false`) hides the warning logged once when `unstable_batchedUpdates` is imported on React Native 0.86+, where it [does nothing](https://github.com/react/react-native/commit/1a623a826654db4238cddc22fb958ccb76207a74) and just calls the callback.
74
60
 
75
- | Option | Type | Default | Description |
76
- | -------------------- | -------- | ----------------------------- | -------------------------------------------------------------------- |
77
- | `reactNativeVersion` | `string` | latest map in [`maps/`](maps) | React Native version to use. Loads `maps/<reactNativeVersion>.json`. |
61
+ ## Notes
78
62
 
79
- Maps are available for every stable React Native release from `0.70.0` on. The version must match a map exactly. If it doesn't, the build fails with an error listing the available versions. After upgrading React Native to a release that has no map yet, update this plugin as well.
63
+ - Unknown names and type-only imports are left untouched.
64
+ - Re-exports (`export { X } from 'react-native'`) and `require('react-native')` in compiled CommonJS code (e.g. in `node_modules`) are rewritten too.
65
+ - `Platform` stays a local `Platform` variable, so Metro's `Platform.OS` / `Platform.select` inlining keeps working (not for aliases like `Platform as P`).
66
+ - `import * as RN from 'react-native'` and `module.exports = require('react-native')` throw a build error.
67
+ - Generated paths point to React Native internals, which is why every version has its own map.
80
68
 
81
- ## Notes
69
+ ## Compatibility
82
70
 
83
- - Only names listed in the map are rewritten. Unknown names stay on the original `react-native` import.
84
- - Type-only imports (`import type { ... }`, `import { type ... }`) are left untouched.
85
- - `Platform` always stays on the `react-native` import. Metro's `Platform.OS` / `Platform.select` dead-code elimination (`inlinePlatform`) only recognizes `Platform` imported from `'react-native'`.
86
- - Aliases are preserved: `import { Text as RNText }` → `import RNText from 'react-native/Libraries/Text/Text'`.
87
- - `import * as RN from 'react-native'` throws a build error. Use named imports instead.
88
- - The generated paths point to React Native internals (`Libraries/...`, `src/private/...`). They are not public API, which is why every React Native version has its own map.
71
+ - ✅ [Uniwind](https://github.com/uni-stack/uniwind): `withUniwindConfig` also redirects deep `react-native/Libraries/...` imports of the components it styles, so `className` keeps working.
72
+ - ❌ `react-native-worklets` bundle mode: `getBundleModeMetroConfig` resolves `react-native` to its own [shim](https://github.com/software-mansion/react-native-reanimated/blob/main/packages/react-native-worklets/bundleMode/shims/reactNativeShim.js), which sets up the worklet runtime. The deep paths skip it, so don't combine them.
89
73
 
90
74
  ## Generating maps (development)
91
75
 
92
- Maps are generated from each version's `react-native/index.js`:
93
-
94
76
  ```bash
95
- yarn generate-maps
96
- # or for specific versions:
97
- yarn generate-maps 0.87.1 0.86.3
77
+ yarn generate-maps # all versions
78
+ yarn generate-maps 0.87.1 # specific versions
98
79
  ```
99
80
 
100
81
  ## License
package/index.js CHANGED
@@ -15,13 +15,32 @@
15
15
  * '*' -> `require(path)` (the getter returns the whole module)
16
16
  * other -> `require(path).<exportName>`
17
17
  *
18
- * `Platform` is always required as `require('Platform')`, so Metro's
19
- * inline-platform optimization (Platform.OS / Platform.select) keeps working.
18
+ * Re-exports are rewritten the same way:
20
19
  *
21
- * Unknown names and type-only imports are left untouched.
20
+ * export { findNodeHandle } from 'react-native';
21
+ * // ->
22
+ * const _findNodeHandle = require('react-native/Libraries/ReactNative/RendererProxy').findNodeHandle;
23
+ * export { _findNodeHandle as findNodeHandle };
24
+ *
25
+ * `require('react-native')` in compiled CommonJS code is rewritten too. Each
26
+ * usage gets its own inline `require()`, keeping the barrel's lazy getters:
27
+ *
28
+ * var react_native_1 = require('react-native');
29
+ * react_native_1.Alert.alert('Hi');
30
+ * const { View } = require('react-native');
31
+ * // ->
32
+ * require('react-native/Libraries/Alert/Alert').default.alert('Hi');
33
+ * const View = require('react-native/Libraries/Components/View/View').default;
34
+ *
35
+ * The `require('react-native')` binding is removed only when every usage was
36
+ * rewritten (`x.Unknown`, `foo(x)`, ... keep it).
37
+ *
38
+ * Unknown names and type-only imports/exports are left untouched.
22
39
  *
23
40
  * Options:
24
41
  * reactNativeVersion - picks `maps/<version>.json` (defaults to the latest map)
42
+ * silenceBatchedUpdatesWarning - hides the `unstable_batchedUpdates` no-op
43
+ * warning on 0.86+
25
44
  */
26
45
 
27
46
  const fs = require('fs');
@@ -29,10 +48,10 @@ const nodePath = require('path');
29
48
 
30
49
  const RN = 'react-native';
31
50
 
32
- const PLATFORM = 'Platform';
33
-
34
51
  const MAPS_DIR = nodePath.join(__dirname, 'maps');
35
52
 
53
+ let warnedBatchedUpdates = false;
54
+
36
55
  const compareVersions = (a, b) => {
37
56
  const pa = a.split('.').map(Number);
38
57
  const pb = b.split('.').map(Number);
@@ -65,27 +84,238 @@ const loadMap = (version) => {
65
84
 
66
85
  module.exports = function reactNativeDirectImports(
67
86
  { types: t },
68
- { reactNativeVersion } = {},
87
+ { reactNativeVersion, silenceBatchedUpdatesWarning = false } = {},
69
88
  ) {
70
89
  const MAP = loadMap(reactNativeVersion);
71
90
 
72
- const buildRequire = (source, exportName, local) => {
91
+ const buildRequire = (source, exportName) => {
73
92
  const call = t.callExpression(t.identifier('require'), [
74
93
  t.stringLiteral(source),
75
94
  ]);
76
- return t.variableDeclaration('const', [
77
- t.variableDeclarator(
78
- local,
79
- exportName === '*'
80
- ? call
81
- : t.memberExpression(call, t.identifier(exportName)),
82
- ),
83
- ]);
95
+ return exportName === '*'
96
+ ? call
97
+ : t.memberExpression(call, t.identifier(exportName));
98
+ };
99
+
100
+ const nameOf = (node) => (t.isIdentifier(node) ? node.name : node.value);
101
+
102
+ // Since 0.86 `unstable_batchedUpdates` is a plain method in
103
+ // `react-native/index.js` (no getter, no module to require), so it gets
104
+ // inlined: `(fn, bookkeeping) => fn(bookkeeping)`.
105
+ const buildBatchedUpdates = () => {
106
+ if (!silenceBatchedUpdatesWarning && !warnedBatchedUpdates) {
107
+ warnedBatchedUpdates = true;
108
+ console.warn(
109
+ '[react-native-direct-imports] `unstable_batchedUpdates` does nothing since react-native 0.86, it just calls the callback: https://github.com/react/react-native/commit/1a623a826654db4238cddc22fb958ccb76207a74. Pass `silenceBatchedUpdatesWarning: true` to hide this warning.',
110
+ );
111
+ }
112
+ const fn = t.identifier('fn');
113
+ const bookkeeping = t.identifier('bookkeeping');
114
+ return t.arrowFunctionExpression(
115
+ [fn, bookkeeping],
116
+ t.callExpression(fn, [bookkeeping]),
117
+ );
118
+ };
119
+
120
+ // Returns the direct `require()` expression for a name from
121
+ // `react-native`, or `null` if the name is not in the map.
122
+ const buildDirectExpression = (importedName) => {
123
+ const entry = MAP[importedName];
124
+ if (!entry && importedName === 'unstable_batchedUpdates') {
125
+ return buildBatchedUpdates();
126
+ }
127
+ if (!entry) return null;
128
+ const [modulePath, exportName] = entry;
129
+ return buildRequire(`${RN}/${modulePath}`, exportName);
130
+ };
131
+
132
+ // Returns the `require()` declaration for a name from `react-native`, or
133
+ // `null` if the name is not in the map.
134
+ const buildDirect = (importedName, local) => {
135
+ const expression = buildDirectExpression(importedName);
136
+ return (
137
+ expression &&
138
+ t.variableDeclaration('const', [t.variableDeclarator(local, expression)])
139
+ );
140
+ };
141
+
142
+ // `x.View` / `x['View']` -> 'View', anything else -> null
143
+ const memberName = (node) => {
144
+ if (!t.isMemberExpression(node)) return null;
145
+ if (!node.computed && t.isIdentifier(node.property)) {
146
+ return node.property.name;
147
+ }
148
+ if (node.computed && t.isStringLiteral(node.property)) {
149
+ return node.property.value;
150
+ }
151
+ return null;
152
+ };
153
+
154
+ // `require('react-native')`, also wrapped in `(... as T)`, `(...)!`, `(...)`.
155
+ const isRequireOfReactNative = (node, scope) => {
156
+ while (
157
+ t.isTSAsExpression(node) ||
158
+ t.isTSSatisfiesExpression(node) ||
159
+ t.isTSNonNullExpression(node) ||
160
+ t.isTSTypeAssertion(node) ||
161
+ t.isTypeCastExpression(node) ||
162
+ t.isParenthesizedExpression(node)
163
+ ) {
164
+ node = node.expression;
165
+ }
166
+ return (
167
+ t.isCallExpression(node) &&
168
+ t.isIdentifier(node.callee, { name: 'require' }) &&
169
+ !scope.hasBinding('require') &&
170
+ node.arguments.length === 1 &&
171
+ t.isStringLiteral(node.arguments[0], { value: RN })
172
+ );
173
+ };
174
+
175
+ // Metro's `inlinePlatform` only inlines `Platform.OS` / `Platform.select`
176
+ // on an identifier named `Platform`, so `x.Platform` is pointed at a single
177
+ // `var Platform = require(...)` added at the top of the file. Returns `null`
178
+ // if `Platform` is already taken at the usage site.
179
+ const platformIdentifier = (memberPath, state) => {
180
+ const binding = memberPath.scope.getBinding('Platform');
181
+
182
+ if (state.platformDeclarator) {
183
+ return binding?.path.node === state.platformDeclarator
184
+ ? t.identifier('Platform')
185
+ : null;
186
+ }
187
+
188
+ const program = memberPath.scope.getProgramParent();
189
+ if (binding || program.hasGlobal('Platform')) return null;
190
+
191
+ const declarator = t.variableDeclarator(
192
+ t.identifier('Platform'),
193
+ buildDirectExpression('Platform'),
194
+ );
195
+ const [declarationPath] = program.path.unshiftContainer(
196
+ 'body',
197
+ t.variableDeclaration('var', [declarator]),
198
+ );
199
+ program.registerDeclaration(declarationPath);
200
+ state.platformDeclarator = declarator;
201
+
202
+ return t.identifier('Platform');
203
+ };
204
+
205
+ // Replaces `x.View` with the direct `require()` expression. Returns `false`
206
+ // if the member can't be rewritten.
207
+ const replaceMember = (memberPath, state) => {
208
+ const { parentPath } = memberPath;
209
+ if (
210
+ (parentPath.isAssignmentExpression() &&
211
+ parentPath.node.left === memberPath.node) ||
212
+ parentPath.isUpdateExpression() ||
213
+ parentPath.isUnaryExpression({ operator: 'delete' })
214
+ ) {
215
+ return false;
216
+ }
217
+
218
+ const name = memberName(memberPath.node);
219
+ const expression =
220
+ (name === 'Platform' &&
221
+ MAP.Platform &&
222
+ platformIdentifier(memberPath, state)) ||
223
+ buildDirectExpression(name);
224
+ if (!expression) return false;
225
+
226
+ memberPath.replaceWith(expression);
227
+ return true;
228
+ };
229
+
230
+ // var x = require('react-native');
231
+ // x.View; x.Platform.OS;
232
+ const rewriteBinding = (declaratorPath, state) => {
233
+ const { name } = declaratorPath.node.id;
234
+ const binding = declaratorPath.scope.getBinding(name);
235
+ if (!binding || binding.path !== declaratorPath || !binding.constant) {
236
+ return;
237
+ }
238
+
239
+ let rewroteAll = true;
240
+ for (const ref of binding.referencePaths) {
241
+ const memberPath = ref.parentPath;
242
+ const rewritten =
243
+ memberPath.isMemberExpression() &&
244
+ memberPath.node.object === ref.node &&
245
+ replaceMember(memberPath, state);
246
+ if (!rewritten) rewroteAll = false;
247
+ }
248
+
249
+ if (rewroteAll) declaratorPath.remove();
250
+ };
251
+
252
+ // const { View, Text: RNText } = require('react-native');
253
+ const rewritePattern = (declaratorPath) => {
254
+ const { node } = declaratorPath;
255
+ const kept = [];
256
+ const direct = [];
257
+
258
+ for (const prop of node.id.properties) {
259
+ const expression =
260
+ t.isObjectProperty(prop) &&
261
+ !prop.computed &&
262
+ t.isIdentifier(prop.value) &&
263
+ buildDirectExpression(nameOf(prop.key));
264
+
265
+ if (!expression) {
266
+ kept.push(prop);
267
+ continue;
268
+ }
269
+
270
+ direct.push(t.variableDeclarator(prop.value, expression));
271
+ }
272
+
273
+ if (direct.length === 0) return;
274
+
275
+ if (kept.length > 0) {
276
+ node.id.properties = kept;
277
+ declaratorPath.insertAfter(direct);
278
+ } else {
279
+ declaratorPath.replaceWithMultiple(direct);
280
+ }
84
281
  };
85
282
 
86
283
  return {
87
284
  name: 'react-native-direct-imports',
88
285
  visitor: {
286
+ // Rewrites happen on the replaced node itself (not from the inner
287
+ // `require()` call), so other plugins visiting the same nodes don't
288
+ // see detached paths.
289
+ AssignmentExpression(path) {
290
+ const { node } = path;
291
+ if (
292
+ path.get('left').matchesPattern('module.exports') &&
293
+ isRequireOfReactNative(node.right, path.scope)
294
+ ) {
295
+ throw path.buildCodeFrameError(
296
+ "`module.exports = require('react-native')` is not allowed, re-export named values instead: `exports.View = require('react-native').View`",
297
+ );
298
+ }
299
+ },
300
+
301
+ // require('react-native').Linking
302
+ MemberExpression(path, state) {
303
+ if (isRequireOfReactNative(path.node.object, path.scope)) {
304
+ replaceMember(path, state);
305
+ }
306
+ },
307
+
308
+ VariableDeclarator(path, state) {
309
+ const { node } = path;
310
+ if (!isRequireOfReactNative(node.init, path.scope)) return;
311
+
312
+ if (t.isIdentifier(node.id)) {
313
+ rewriteBinding(path, state);
314
+ } else if (t.isObjectPattern(node.id)) {
315
+ rewritePattern(path);
316
+ }
317
+ },
318
+
89
319
  ImportDeclaration(path) {
90
320
  const { node } = path;
91
321
  if (node.source.value !== RN || node.importKind === 'type') return;
@@ -102,37 +332,70 @@ module.exports = function reactNativeDirectImports(
102
332
  const direct = [];
103
333
 
104
334
  for (const spec of node.specifiers) {
105
- const importedName =
335
+ const declaration =
106
336
  t.isImportSpecifier(spec) &&
107
337
  spec.importKind !== 'type' &&
108
- (t.isIdentifier(spec.imported)
109
- ? spec.imported.name
110
- : spec.imported.value);
111
- const local = t.identifier(spec.local.name);
338
+ buildDirect(nameOf(spec.imported), t.identifier(spec.local.name));
112
339
 
113
- if (importedName === PLATFORM) {
114
- direct.push(buildRequire(PLATFORM, '*', local));
340
+ if (!declaration) {
341
+ kept.push(spec);
115
342
  continue;
116
343
  }
117
344
 
118
- const entry = importedName && MAP[importedName];
345
+ direct.push(declaration);
346
+ }
119
347
 
120
- if (!entry) {
348
+ if (direct.length === 0) return;
349
+
350
+ if (kept.length > 0) {
351
+ node.specifiers = kept;
352
+ path.insertAfter(direct);
353
+ } else {
354
+ path.replaceWithMultiple(direct);
355
+ }
356
+ },
357
+
358
+ ExportNamedDeclaration(path) {
359
+ const { node } = path;
360
+ if (node.source?.value !== RN || node.exportKind === 'type') return;
361
+
362
+ const kept = [];
363
+ const direct = [];
364
+ const reexported = [];
365
+
366
+ for (const spec of node.specifiers) {
367
+ if (!t.isExportSpecifier(spec) || spec.exportKind === 'type') {
121
368
  kept.push(spec);
122
369
  continue;
123
370
  }
124
371
 
125
- const [modulePath, exportName] = entry;
126
- direct.push(buildRequire(`${RN}/${modulePath}`, exportName, local));
372
+ const importedName = nameOf(spec.local);
373
+ const local = path.scope.generateUidIdentifier(importedName);
374
+ const declaration = buildDirect(importedName, local);
375
+
376
+ if (!declaration) {
377
+ kept.push(spec);
378
+ continue;
379
+ }
380
+
381
+ direct.push(declaration);
382
+ reexported.push(
383
+ t.exportSpecifier(t.identifier(local.name), spec.exported),
384
+ );
127
385
  }
128
386
 
129
387
  if (direct.length === 0) return;
130
388
 
389
+ const replacement = [
390
+ ...direct,
391
+ t.exportNamedDeclaration(null, reexported),
392
+ ];
393
+
131
394
  if (kept.length > 0) {
132
395
  node.specifiers = kept;
133
- path.insertAfter(direct);
396
+ path.insertAfter(replacement);
134
397
  } else {
135
- path.replaceWithMultiple(direct);
398
+ path.replaceWithMultiple(replacement);
136
399
  }
137
400
  },
138
401
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "babel-plugin-react-native-direct-imports",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Babel plugin that rewrites `react-native` barrel imports into direct module imports",
5
5
  "main": "index.js",
6
6
  "files": [