babel-plugin-react-native-direct-imports 1.0.2 → 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 (3) hide show
  1. package/README.md +13 -2
  2. package/index.js +280 -27
  3. package/package.json +1 -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
@@ -15,10 +15,27 @@
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)
@@ -29,8 +46,6 @@ const nodePath = require('path');
29
46
 
30
47
  const RN = 'react-native';
31
48
 
32
- const PLATFORM = 'Platform';
33
-
34
49
  const MAPS_DIR = nodePath.join(__dirname, 'maps');
35
50
 
36
51
  const compareVersions = (a, b) => {
@@ -69,23 +84,228 @@ module.exports = function reactNativeDirectImports(
69
84
  ) {
70
85
  const MAP = loadMap(reactNativeVersion);
71
86
 
72
- const buildRequire = (source, exportName, local) => {
87
+ const buildRequire = (source, exportName) => {
73
88
  const call = t.callExpression(t.identifier('require'), [
74
89
  t.stringLiteral(source),
75
90
  ]);
76
- return t.variableDeclaration('const', [
77
- t.variableDeclarator(
78
- local,
79
- exportName === '*'
80
- ? call
81
- : t.memberExpression(call, t.identifier(exportName)),
82
- ),
83
- ]);
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
+ }
84
271
  };
85
272
 
86
273
  return {
87
274
  name: 'react-native-direct-imports',
88
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
+
89
309
  ImportDeclaration(path) {
90
310
  const { node } = path;
91
311
  if (node.source.value !== RN || node.importKind === 'type') return;
@@ -102,37 +322,70 @@ module.exports = function reactNativeDirectImports(
102
322
  const direct = [];
103
323
 
104
324
  for (const spec of node.specifiers) {
105
- const importedName =
325
+ const declaration =
106
326
  t.isImportSpecifier(spec) &&
107
327
  spec.importKind !== 'type' &&
108
- (t.isIdentifier(spec.imported)
109
- ? spec.imported.name
110
- : spec.imported.value);
111
- const local = t.identifier(spec.local.name);
328
+ buildDirect(nameOf(spec.imported), t.identifier(spec.local.name));
329
+
330
+ if (!declaration) {
331
+ kept.push(spec);
332
+ continue;
333
+ }
334
+
335
+ direct.push(declaration);
336
+ }
337
+
338
+ if (direct.length === 0) return;
339
+
340
+ if (kept.length > 0) {
341
+ node.specifiers = kept;
342
+ path.insertAfter(direct);
343
+ } else {
344
+ path.replaceWithMultiple(direct);
345
+ }
346
+ },
112
347
 
113
- if (importedName === PLATFORM) {
114
- direct.push(buildRequire(PLATFORM, '*', local));
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);
115
359
  continue;
116
360
  }
117
361
 
118
- const entry = importedName && MAP[importedName];
362
+ const importedName = nameOf(spec.local);
363
+ const local = path.scope.generateUidIdentifier(importedName);
364
+ const declaration = buildDirect(importedName, local);
119
365
 
120
- if (!entry) {
366
+ if (!declaration) {
121
367
  kept.push(spec);
122
368
  continue;
123
369
  }
124
370
 
125
- const [modulePath, exportName] = entry;
126
- direct.push(buildRequire(`${RN}/${modulePath}`, exportName, local));
371
+ direct.push(declaration);
372
+ reexported.push(
373
+ t.exportSpecifier(t.identifier(local.name), spec.exported),
374
+ );
127
375
  }
128
376
 
129
377
  if (direct.length === 0) return;
130
378
 
379
+ const replacement = [
380
+ ...direct,
381
+ t.exportNamedDeclaration(null, reexported),
382
+ ];
383
+
131
384
  if (kept.length > 0) {
132
385
  node.specifiers = kept;
133
- path.insertAfter(direct);
386
+ path.insertAfter(replacement);
134
387
  } else {
135
- path.replaceWithMultiple(direct);
388
+ path.replaceWithMultiple(replacement);
136
389
  }
137
390
  },
138
391
  },
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.0.3",
4
4
  "description": "Babel plugin that rewrites `react-native` barrel imports into direct module imports",
5
5
  "main": "index.js",
6
6
  "files": [