babel-plugin-react-native-direct-imports 1.0.1 → 1.0.3

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 (100) hide show
  1. package/README.md +13 -2
  2. package/index.js +297 -36
  3. package/maps/0.70.0.json +65 -65
  4. package/maps/0.70.1.json +65 -65
  5. package/maps/0.70.10.json +65 -65
  6. package/maps/0.70.11.json +65 -65
  7. package/maps/0.70.12.json +65 -65
  8. package/maps/0.70.13.json +65 -65
  9. package/maps/0.70.14.json +65 -65
  10. package/maps/0.70.15.json +65 -65
  11. package/maps/0.70.2.json +65 -65
  12. package/maps/0.70.3.json +65 -65
  13. package/maps/0.70.4.json +65 -65
  14. package/maps/0.70.5.json +65 -65
  15. package/maps/0.70.6.json +65 -65
  16. package/maps/0.70.7.json +65 -65
  17. package/maps/0.70.8.json +65 -65
  18. package/maps/0.70.9.json +65 -65
  19. package/maps/0.71.0.json +58 -58
  20. package/maps/0.71.1.json +58 -58
  21. package/maps/0.71.10.json +58 -58
  22. package/maps/0.71.11.json +58 -58
  23. package/maps/0.71.12.json +58 -58
  24. package/maps/0.71.13.json +58 -58
  25. package/maps/0.71.14.json +58 -58
  26. package/maps/0.71.15.json +58 -58
  27. package/maps/0.71.16.json +58 -58
  28. package/maps/0.71.17.json +58 -58
  29. package/maps/0.71.18.json +58 -58
  30. package/maps/0.71.19.json +58 -58
  31. package/maps/0.71.2.json +58 -58
  32. package/maps/0.71.3.json +58 -58
  33. package/maps/0.71.4.json +58 -58
  34. package/maps/0.71.5.json +58 -58
  35. package/maps/0.71.6.json +58 -58
  36. package/maps/0.71.7.json +58 -58
  37. package/maps/0.71.8.json +58 -58
  38. package/maps/0.71.9.json +58 -58
  39. package/maps/0.72.0.json +47 -47
  40. package/maps/0.72.1.json +47 -47
  41. package/maps/0.72.10.json +47 -47
  42. package/maps/0.72.11.json +47 -47
  43. package/maps/0.72.12.json +47 -47
  44. package/maps/0.72.13.json +47 -47
  45. package/maps/0.72.14.json +47 -47
  46. package/maps/0.72.15.json +47 -47
  47. package/maps/0.72.17.json +47 -47
  48. package/maps/0.72.2.json +47 -47
  49. package/maps/0.72.3.json +47 -47
  50. package/maps/0.72.4.json +47 -47
  51. package/maps/0.72.5.json +47 -47
  52. package/maps/0.72.6.json +47 -47
  53. package/maps/0.72.7.json +47 -47
  54. package/maps/0.72.8.json +47 -47
  55. package/maps/0.72.9.json +47 -47
  56. package/maps/0.73.0.json +47 -47
  57. package/maps/0.73.1.json +47 -47
  58. package/maps/0.73.10.json +47 -47
  59. package/maps/0.73.11.json +47 -47
  60. package/maps/0.73.2.json +47 -47
  61. package/maps/0.73.3.json +47 -47
  62. package/maps/0.73.4.json +47 -47
  63. package/maps/0.73.5.json +47 -47
  64. package/maps/0.73.6.json +47 -47
  65. package/maps/0.73.7.json +47 -47
  66. package/maps/0.73.8.json +47 -47
  67. package/maps/0.73.9.json +47 -47
  68. package/maps/0.74.0.json +44 -44
  69. package/maps/0.74.1.json +44 -44
  70. package/maps/0.74.2.json +44 -44
  71. package/maps/0.74.3.json +44 -44
  72. package/maps/0.74.4.json +44 -44
  73. package/maps/0.74.5.json +44 -44
  74. package/maps/0.74.6.json +44 -44
  75. package/maps/0.74.7.json +44 -44
  76. package/maps/0.75.0.json +44 -44
  77. package/maps/0.75.1.json +44 -44
  78. package/maps/0.75.2.json +44 -44
  79. package/maps/0.75.3.json +44 -44
  80. package/maps/0.75.4.json +44 -44
  81. package/maps/0.75.5.json +44 -44
  82. package/maps/0.76.0.json +43 -43
  83. package/maps/0.76.1.json +43 -43
  84. package/maps/0.76.2.json +43 -43
  85. package/maps/0.76.3.json +43 -43
  86. package/maps/0.76.4.json +43 -43
  87. package/maps/0.76.5.json +43 -43
  88. package/maps/0.76.6.json +43 -43
  89. package/maps/0.76.7.json +43 -43
  90. package/maps/0.76.8.json +43 -43
  91. package/maps/0.76.9.json +43 -43
  92. package/maps/0.77.0.json +44 -44
  93. package/maps/0.77.1.json +44 -44
  94. package/maps/0.77.2.json +44 -44
  95. package/maps/0.77.3.json +44 -44
  96. package/maps/0.78.0.json +44 -44
  97. package/maps/0.78.1.json +44 -44
  98. package/maps/0.78.2.json +44 -44
  99. package/maps/0.78.3.json +44 -44
  100. package/package.json +2 -1
package/README.md CHANGED
@@ -81,12 +81,23 @@ Maps are available for every stable React Native release from `0.70.0` on. The v
81
81
  ## Notes
82
82
 
83
83
  - Only names listed in the map are rewritten. Unknown names stay on the original `react-native` import.
84
+ - `unstable_batchedUpdates` has no module of its own since React Native 0.86 (it's a plain method in `index.js`), so it is inlined as `const unstable_batchedUpdates = (fn, bookkeeping) => fn(bookkeeping);`, matching React Native's implementation.
84
85
  - 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
+ - Metro's `Platform.OS` / `Platform.select` inlining (`inlinePlatform`) keeps working, as it matches the local name `Platform`. Aliased imports (`import { Platform as P }`) are not inlined.
86
87
  - 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
+ - Re-exports are rewritten too: `export { findNodeHandle } from 'react-native'` → `const _findNodeHandle = require('react-native/Libraries/ReactNative/RendererProxy').findNodeHandle; export { _findNodeHandle as findNodeHandle };`. `export * from 'react-native'` is left untouched.
89
+ - `require('react-native')` in compiled CommonJS code (e.g. TypeScript/Babel output in `node_modules`) is rewritten too: `x.Alert` on `var x = require('react-native')`, `const { View } = require('react-native')` and `require('react-native').Linking`. Each `x.Name` usage becomes its own inline `require()`, so modules are still loaded lazily, like the barrel's getters. The `require('react-native')` itself is kept if any usage can't be rewritten (unknown names, `foo(x)`, ...). `x.Platform` is the exception: it's pointed at a single `var Platform = require('react-native/Libraries/Utilities/Platform').default;` added at the top of the file, so Metro's `inlinePlatform` still matches `Platform.OS` / `Platform.select` (if `Platform` is already declared in that scope, the `require()` is inlined instead).
90
+ - `import * as RN from 'react-native'` and `module.exports = require('react-native')` throw a build error. Use named imports / exports instead.
88
91
  - 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.
89
92
 
93
+ ## Limitations
94
+
95
+ ### `react-native-worklets` bundle mode
96
+
97
+ In bundle mode, `react-native-worklets` uses `getBundleModeMetroConfig` to resolve every `react-native` import to its own [`reactNativeShim.js`](https://github.com/software-mansion/react-native-reanimated/blob/main/packages/react-native-worklets/bundleMode/shims/reactNativeShim.js). The shim sets up `globalThis.__RUNTIME_KIND` (and, on worklet runtimes in dev, guards `__fbBatchedBridgeConfig`) before re-exporting `require('react-native')`.
98
+
99
+ This plugin rewrites `react-native` imports to deep `react-native/Libraries/...` paths, so they no longer resolve to the shim and its setup is skipped. Don't use the plugin together with worklets bundle mode.
100
+
90
101
  ## Generating maps (development)
91
102
 
92
103
  Maps are generated from each version's `react-native/index.js`:
package/index.js CHANGED
@@ -1,22 +1,41 @@
1
1
  /**
2
- * Rewrites named imports from `react-native` to direct imports of the
3
- * underlying modules, so Metro doesn't need to go through the barrel file.
2
+ * Rewrites named imports from `react-native` to direct `require()` calls of
3
+ * the underlying modules, so Metro doesn't need to go through the barrel file.
4
+ * Plain `require()` is used instead of `import` so Babel doesn't add
5
+ * interop helpers (`_interopRequireDefault`, ...) for every module.
4
6
  *
5
7
  * import { View, AppRegistry, Systrace } from 'react-native';
6
8
  * // ->
7
- * import View from 'react-native/Libraries/Components/View/View';
8
- * import { AppRegistry } from 'react-native/Libraries/ReactNative/AppRegistry';
9
- * import * as Systrace from 'react-native/Libraries/Performance/Systrace';
9
+ * const View = require('react-native/Libraries/Components/View/View').default;
10
+ * const AppRegistry = require('react-native/Libraries/ReactNative/AppRegistry').AppRegistry;
11
+ * const Systrace = require('react-native/Libraries/Performance/Systrace');
10
12
  *
11
- * Map value format: [path, exportName]
12
- * 'default' -> default import
13
- * '*' -> namespace import (module is used as a whole, no `.default`)
14
- * other -> named import
13
+ * Map value format: [path, exportName], mirroring the getter in
14
+ * `react-native/index.js`:
15
+ * '*' -> `require(path)` (the getter returns the whole module)
16
+ * other -> `require(path).<exportName>`
15
17
  *
16
- * Unknown names, type-only imports and `Platform` are left untouched.
17
- * `Platform` stays on `react-native` because Metro's inline-platform
18
- * optimization (Platform.OS / Platform.select dead-code elimination) only
19
- * recognizes it when imported from 'react-native' directly.
18
+ * Re-exports are rewritten the same way:
19
+ *
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.
20
39
  *
21
40
  * Options:
22
41
  * reactNativeVersion - picks `maps/<version>.json` (defaults to the latest map)
@@ -27,9 +46,6 @@ const nodePath = require('path');
27
46
 
28
47
  const RN = 'react-native';
29
48
 
30
- // Kept on the `react-native` import so Metro can still inline them.
31
- const KEEP = new Set(['Platform']);
32
-
33
49
  const MAPS_DIR = nodePath.join(__dirname, 'maps');
34
50
 
35
51
  const compareVersions = (a, b) => {
@@ -68,15 +84,228 @@ module.exports = function reactNativeDirectImports(
68
84
  ) {
69
85
  const MAP = loadMap(reactNativeVersion);
70
86
 
71
- const buildSpecifier = (exportName, local) => {
72
- if (exportName === 'default') return t.importDefaultSpecifier(local);
73
- if (exportName === '*') return t.importNamespaceSpecifier(local);
74
- return t.importSpecifier(local, t.identifier(exportName));
87
+ const buildRequire = (source, exportName) => {
88
+ const call = t.callExpression(t.identifier('require'), [
89
+ t.stringLiteral(source),
90
+ ]);
91
+ return exportName === '*'
92
+ ? call
93
+ : t.memberExpression(call, t.identifier(exportName));
94
+ };
95
+
96
+ const nameOf = (node) => (t.isIdentifier(node) ? node.name : node.value);
97
+
98
+ // Since 0.86 `unstable_batchedUpdates` is a plain method in
99
+ // `react-native/index.js` (no getter, no module to require), so it gets
100
+ // inlined: `(fn, bookkeeping) => fn(bookkeeping)`.
101
+ const buildBatchedUpdates = () => {
102
+ const fn = t.identifier('fn');
103
+ const bookkeeping = t.identifier('bookkeeping');
104
+ return t.arrowFunctionExpression(
105
+ [fn, bookkeeping],
106
+ t.callExpression(fn, [bookkeeping]),
107
+ );
108
+ };
109
+
110
+ // Returns the direct `require()` expression for a name from
111
+ // `react-native`, or `null` if the name is not in the map.
112
+ const buildDirectExpression = (importedName) => {
113
+ const entry = MAP[importedName];
114
+ if (!entry && importedName === 'unstable_batchedUpdates') {
115
+ return buildBatchedUpdates();
116
+ }
117
+ if (!entry) return null;
118
+ const [modulePath, exportName] = entry;
119
+ return buildRequire(`${RN}/${modulePath}`, exportName);
120
+ };
121
+
122
+ // Returns the `require()` declaration for a name from `react-native`, or
123
+ // `null` if the name is not in the map.
124
+ const buildDirect = (importedName, local) => {
125
+ const expression = buildDirectExpression(importedName);
126
+ return (
127
+ expression &&
128
+ t.variableDeclaration('const', [t.variableDeclarator(local, expression)])
129
+ );
130
+ };
131
+
132
+ // `x.View` / `x['View']` -> 'View', anything else -> null
133
+ const memberName = (node) => {
134
+ if (!t.isMemberExpression(node)) return null;
135
+ if (!node.computed && t.isIdentifier(node.property)) {
136
+ return node.property.name;
137
+ }
138
+ if (node.computed && t.isStringLiteral(node.property)) {
139
+ return node.property.value;
140
+ }
141
+ return null;
142
+ };
143
+
144
+ // `require('react-native')`, also wrapped in `(... as T)`, `(...)!`, `(...)`.
145
+ const isRequireOfReactNative = (node, scope) => {
146
+ while (
147
+ t.isTSAsExpression(node) ||
148
+ t.isTSSatisfiesExpression(node) ||
149
+ t.isTSNonNullExpression(node) ||
150
+ t.isTSTypeAssertion(node) ||
151
+ t.isTypeCastExpression(node) ||
152
+ t.isParenthesizedExpression(node)
153
+ ) {
154
+ node = node.expression;
155
+ }
156
+ return (
157
+ t.isCallExpression(node) &&
158
+ t.isIdentifier(node.callee, { name: 'require' }) &&
159
+ !scope.hasBinding('require') &&
160
+ node.arguments.length === 1 &&
161
+ t.isStringLiteral(node.arguments[0], { value: RN })
162
+ );
163
+ };
164
+
165
+ // Metro's `inlinePlatform` only inlines `Platform.OS` / `Platform.select`
166
+ // on an identifier named `Platform`, so `x.Platform` is pointed at a single
167
+ // `var Platform = require(...)` added at the top of the file. Returns `null`
168
+ // if `Platform` is already taken at the usage site.
169
+ const platformIdentifier = (memberPath, state) => {
170
+ const binding = memberPath.scope.getBinding('Platform');
171
+
172
+ if (state.platformDeclarator) {
173
+ return binding?.path.node === state.platformDeclarator
174
+ ? t.identifier('Platform')
175
+ : null;
176
+ }
177
+
178
+ const program = memberPath.scope.getProgramParent();
179
+ if (binding || program.hasGlobal('Platform')) return null;
180
+
181
+ const declarator = t.variableDeclarator(
182
+ t.identifier('Platform'),
183
+ buildDirectExpression('Platform'),
184
+ );
185
+ const [declarationPath] = program.path.unshiftContainer(
186
+ 'body',
187
+ t.variableDeclaration('var', [declarator]),
188
+ );
189
+ program.registerDeclaration(declarationPath);
190
+ state.platformDeclarator = declarator;
191
+
192
+ return t.identifier('Platform');
193
+ };
194
+
195
+ // Replaces `x.View` with the direct `require()` expression. Returns `false`
196
+ // if the member can't be rewritten.
197
+ const replaceMember = (memberPath, state) => {
198
+ const { parentPath } = memberPath;
199
+ if (
200
+ (parentPath.isAssignmentExpression() &&
201
+ parentPath.node.left === memberPath.node) ||
202
+ parentPath.isUpdateExpression() ||
203
+ parentPath.isUnaryExpression({ operator: 'delete' })
204
+ ) {
205
+ return false;
206
+ }
207
+
208
+ const name = memberName(memberPath.node);
209
+ const expression =
210
+ (name === 'Platform' &&
211
+ MAP.Platform &&
212
+ platformIdentifier(memberPath, state)) ||
213
+ buildDirectExpression(name);
214
+ if (!expression) return false;
215
+
216
+ memberPath.replaceWith(expression);
217
+ return true;
218
+ };
219
+
220
+ // var x = require('react-native');
221
+ // x.View; x.Platform.OS;
222
+ const rewriteBinding = (declaratorPath, state) => {
223
+ const { name } = declaratorPath.node.id;
224
+ const binding = declaratorPath.scope.getBinding(name);
225
+ if (!binding || binding.path !== declaratorPath || !binding.constant) {
226
+ return;
227
+ }
228
+
229
+ let rewroteAll = true;
230
+ for (const ref of binding.referencePaths) {
231
+ const memberPath = ref.parentPath;
232
+ const rewritten =
233
+ memberPath.isMemberExpression() &&
234
+ memberPath.node.object === ref.node &&
235
+ replaceMember(memberPath, state);
236
+ if (!rewritten) rewroteAll = false;
237
+ }
238
+
239
+ if (rewroteAll) declaratorPath.remove();
240
+ };
241
+
242
+ // const { View, Text: RNText } = require('react-native');
243
+ const rewritePattern = (declaratorPath) => {
244
+ const { node } = declaratorPath;
245
+ const kept = [];
246
+ const direct = [];
247
+
248
+ for (const prop of node.id.properties) {
249
+ const expression =
250
+ t.isObjectProperty(prop) &&
251
+ !prop.computed &&
252
+ t.isIdentifier(prop.value) &&
253
+ buildDirectExpression(nameOf(prop.key));
254
+
255
+ if (!expression) {
256
+ kept.push(prop);
257
+ continue;
258
+ }
259
+
260
+ direct.push(t.variableDeclarator(prop.value, expression));
261
+ }
262
+
263
+ if (direct.length === 0) return;
264
+
265
+ if (kept.length > 0) {
266
+ node.id.properties = kept;
267
+ declaratorPath.insertAfter(direct);
268
+ } else {
269
+ declaratorPath.replaceWithMultiple(direct);
270
+ }
75
271
  };
76
272
 
77
273
  return {
78
274
  name: 'react-native-direct-imports',
79
275
  visitor: {
276
+ // Rewrites happen on the replaced node itself (not from the inner
277
+ // `require()` call), so other plugins visiting the same nodes don't
278
+ // see detached paths.
279
+ AssignmentExpression(path) {
280
+ const { node } = path;
281
+ if (
282
+ path.get('left').matchesPattern('module.exports') &&
283
+ isRequireOfReactNative(node.right, path.scope)
284
+ ) {
285
+ throw path.buildCodeFrameError(
286
+ "`module.exports = require('react-native')` is not allowed, re-export named values instead: `exports.View = require('react-native').View`",
287
+ );
288
+ }
289
+ },
290
+
291
+ // require('react-native').Linking
292
+ MemberExpression(path, state) {
293
+ if (isRequireOfReactNative(path.node.object, path.scope)) {
294
+ replaceMember(path, state);
295
+ }
296
+ },
297
+
298
+ VariableDeclarator(path, state) {
299
+ const { node } = path;
300
+ if (!isRequireOfReactNative(node.init, path.scope)) return;
301
+
302
+ if (t.isIdentifier(node.id)) {
303
+ rewriteBinding(path, state);
304
+ } else if (t.isObjectPattern(node.id)) {
305
+ rewritePattern(path);
306
+ }
307
+ },
308
+
80
309
  ImportDeclaration(path) {
81
310
  const { node } = path;
82
311
  if (node.source.value !== RN || node.importKind === 'type') return;
@@ -93,29 +322,17 @@ module.exports = function reactNativeDirectImports(
93
322
  const direct = [];
94
323
 
95
324
  for (const spec of node.specifiers) {
96
- const importedName =
325
+ const declaration =
97
326
  t.isImportSpecifier(spec) &&
98
- (t.isIdentifier(spec.imported)
99
- ? spec.imported.name
100
- : spec.imported.value);
101
- const entry =
102
- importedName &&
103
327
  spec.importKind !== 'type' &&
104
- !KEEP.has(importedName) &&
105
- MAP[importedName];
328
+ buildDirect(nameOf(spec.imported), t.identifier(spec.local.name));
106
329
 
107
- if (!entry) {
330
+ if (!declaration) {
108
331
  kept.push(spec);
109
332
  continue;
110
333
  }
111
334
 
112
- const [modulePath, exportName] = entry;
113
- direct.push(
114
- t.importDeclaration(
115
- [buildSpecifier(exportName, t.identifier(spec.local.name))],
116
- t.stringLiteral(`${RN}/${modulePath}`),
117
- ),
118
- );
335
+ direct.push(declaration);
119
336
  }
120
337
 
121
338
  if (direct.length === 0) return;
@@ -127,6 +344,50 @@ module.exports = function reactNativeDirectImports(
127
344
  path.replaceWithMultiple(direct);
128
345
  }
129
346
  },
347
+
348
+ ExportNamedDeclaration(path) {
349
+ const { node } = path;
350
+ if (node.source?.value !== RN || node.exportKind === 'type') return;
351
+
352
+ const kept = [];
353
+ const direct = [];
354
+ const reexported = [];
355
+
356
+ for (const spec of node.specifiers) {
357
+ if (!t.isExportSpecifier(spec) || spec.exportKind === 'type') {
358
+ kept.push(spec);
359
+ continue;
360
+ }
361
+
362
+ const importedName = nameOf(spec.local);
363
+ const local = path.scope.generateUidIdentifier(importedName);
364
+ const declaration = buildDirect(importedName, local);
365
+
366
+ if (!declaration) {
367
+ kept.push(spec);
368
+ continue;
369
+ }
370
+
371
+ direct.push(declaration);
372
+ reexported.push(
373
+ t.exportSpecifier(t.identifier(local.name), spec.exported),
374
+ );
375
+ }
376
+
377
+ if (direct.length === 0) return;
378
+
379
+ const replacement = [
380
+ ...direct,
381
+ t.exportNamedDeclaration(null, reexported),
382
+ ];
383
+
384
+ if (kept.length > 0) {
385
+ node.specifiers = kept;
386
+ path.insertAfter(replacement);
387
+ } else {
388
+ path.replaceWithMultiple(replacement);
389
+ }
390
+ },
130
391
  },
131
392
  };
132
393
  };