babel-plugin-react-native-direct-imports 1.2.0 → 1.2.1-rc.14

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
@@ -63,8 +63,84 @@ Then reset the Metro cache once (`npx react-native start --reset-cache` or `npx
63
63
 
64
64
  `reactNativeVersion` picks the React Native version to generate imports for (default: the latest known). An unknown version falls back to the closest older map — a `0.88.2` or `0.89.0` app keeps building with the `0.88.1` map — so upgrading React Native no longer breaks the build, though updating the plugin still gets you the exact map. Only a version older than everything the plugin knows (`< 0.70.0`) fails.
65
65
 
66
+ `packages` (default: `[]`) lists other packages to rewrite imports of, see [Other packages](#other-packages).
67
+
68
+ `onModuleReexport` (default: `'error'`) is what happens on `module.exports = require('react-native')` (or of a listed package), which re-exports the whole package and keeps all of it in the bundle: `'error'` fails the build, `'warn'` logs a warning and leaves the code as it is, `'silent'` just leaves it. For listed packages it also covers `const x = require('pkg'); module.exports = x`.
69
+
66
70
  `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.
67
71
 
72
+ ## Other packages
73
+
74
+ The same idea works for other packages. List them in `packages`:
75
+
76
+ ```js
77
+ ['react-native-direct-imports', { packages: ['react-native-svg'] }];
78
+ ```
79
+
80
+ ```js
81
+ import Svg, { Defs, LinearGradient, Path, Rect, Stop } from 'react-native-svg';
82
+
83
+ // ↓ becomes
84
+
85
+ import Svg from 'react-native-svg/src/elements/Svg';
86
+ import Defs from 'react-native-svg/src/elements/Defs';
87
+ import LinearGradient from 'react-native-svg/src/elements/LinearGradient';
88
+ import Path from 'react-native-svg/src/elements/Path';
89
+ import Rect from 'react-native-svg/src/elements/Rect';
90
+ import Stop from 'react-native-svg/src/elements/Stop';
91
+ ```
92
+
93
+ ### Packages with a map
94
+
95
+ | Package | Versions | Rewritten paths |
96
+ | --- | --- | --- |
97
+ | [`react-native-svg`](https://github.com/software-mansion/react-native-svg) | `15.0.0`+ | `src/...` |
98
+ | [`react-native-reanimated`](https://github.com/software-mansion/react-native-reanimated) | `4.0.0`+ | `src/...` |
99
+ | [`react-native-gesture-handler`](https://github.com/software-mansion/react-native-gesture-handler) | `2.0.0`+ | `src/...` |
100
+ | [`react-native-screens`](https://github.com/software-mansion/react-native-screens) | `4.0.0`+ | `src/...` |
101
+ | [`react-native-skia`](https://github.com/wcandillon/react-native-skia) | `3.0.0`+ | `src/...` |
102
+ | [`react-native-keyboard-controller`](https://github.com/kirillzyusko/react-native-keyboard-controller) | `1.20.0`+ | `src/...` |
103
+ | [`react-native-notify-kit`](https://www.npmjs.com/package/react-native-notify-kit) | `10.0.0`+ | `src/...` |
104
+ | [`@gorhom/bottom-sheet`](https://github.com/gorhom/react-native-bottom-sheet) | `5.0.0`+ | `src/...` |
105
+ | [`@sentry/core`](https://github.com/getsentry/sentry-javascript) | `10.0.0`+ | `build/esm/...` |
106
+ | [`@sentry/react-native`](https://github.com/getsentry/sentry-react-native) | `7.0.0`+ | `dist/js/...` |
107
+
108
+ Add the ones you use to `packages`. The deep paths of the `@sentry/*` packages aren't listed in their [`exports`](https://nodejs.org/api/packages.html#exports) field, so Metro needs package exports off (or a `resolveRequest` that allows them) to resolve them.
109
+
110
+ > [!WARNING]
111
+ > A direct import skips everything the package's entry file does when it is loaded. For some of these packages that is **setup code**: `react-native-reanimated` (`initializeReanimatedModule`), `react-native-gesture-handler` (`initialize()` starts the native event receiver), `react-native-skia` (`NativeSetup`) and `react-native-screens` (`NativeScreensModule`). If nothing else in your app loads the package root, that setup never runs. Keep one plain `import 'react-native-reanimated'`-style import (or an import the plugin can't rewrite) in your app's entry file, and test on a device after enabling these.
112
+
113
+ Like `react-native`, these ship a map per version. The version is read from the **installed** package, so there is nothing to configure: an unknown version falls back to the closest older map (a `15.99.0` install uses the `15.16.2` map). A version older than the first map (`< 15.0.0` for `react-native-svg`) throws a build error.
114
+
115
+ ### Any other package
116
+
117
+ A package without a shipped map is resolved from the **installed** package instead: the plugin picks its entry file from the package's `package.json` (`exports["."]`, then `react-native`, `module` and `main`; unlike Metro it prefers `module`, so it can read an ES build when `main` is CommonJS) and follows the re-exports (`export * from`, `export { default as X } from`, `import X from '...'; export { X }`, ...) to the file that defines each name. Only the files on the way to the names you import are parsed, once per process. A package that isn't installed, or whose entry has no ES module exports (a CommonJS-only build), throws a build error instead of silently doing nothing.
118
+
119
+ ### What gets rewritten
120
+
121
+ - Default and named imports and `export { ... } from 'pkg'` re-exports are rewritten; each one becomes its own `import` / `export ... from`. Namespace imports, type imports and names that aren't in the map (or can't be traced to a file inside the package) stay as they are.
122
+ - `require('pkg')` is rewritten like it is for `react-native`, but all or nothing. These are rewritten:
123
+
124
+ ```js
125
+ const { Svg, Path: P } = require('react-native-svg');
126
+ const RNSvg = require('react-native-svg');
127
+ RNSvg.G; RNSvg['Rect'];
128
+ require('react-native-svg').Circle;
129
+
130
+ // ↓ becomes
131
+
132
+ const Svg = require('react-native-svg/src/elements/Svg').default,
133
+ P = require('react-native-svg/src/elements/Path').default;
134
+ require('react-native-svg/src/elements/G').default; // each usage is a lazy inline require
135
+ require('react-native-svg/src/elements/Rect').default;
136
+ require('react-native-svg/src/elements/Circle').default;
137
+ ```
138
+
139
+ If a binding is used any other way, the whole `require` stays as written, because the whole package is loaded through it anyway: `fn(RNSvg)`, `const x = RNSvg`, `RNSvg.Unknown`, `RNSvg.G = ...`, `delete RNSvg.G`, `{ ...RNSvg }`, `Object.keys(RNSvg)`, `RNSvg[name]`, `export const RNSvg = require(...)`, `{ Svg, ...rest } = require(...)`, `{ Svg = fallback } = require(...)`. `module.exports = require('pkg')` and `module.exports = RNSvg` follow [`onModuleReexport`](#usage).
140
+ - `export * from 'pkg'` is not rewritten.
141
+ - Direct imports skip everything else the barrel does, including its side effects.
142
+ - Packages with an [`exports`](https://nodejs.org/api/packages.html#exports) field are resolved through it: the entry is `exports["."]` (conditions `react-native`, `import`, `module`, `default`), and each import gets the public subpath its file is exposed as (`"./shapes/*": "./src/elements/*.ts"` turns `src/elements/Circle.ts` into `pkg/shapes/Circle`). A file that `exports` doesn't expose can't be imported from outside, so that import stays as it is.
143
+
68
144
  ## Notes
69
145
 
70
146
  - Unknown names and type-only imports are left untouched.
@@ -80,15 +156,31 @@ Then reset the Metro cache once (`npx react-native start --reset-cache` or `npx
80
156
 
81
157
  ## Generating maps (development)
82
158
 
83
- The map lives in two shapes:
159
+ Each map lives in two shapes:
84
160
 
85
- - [`maps/<version>.json`](maps) — one pretty-printed file per React Native version. This is the committed source of truth, so adding a version stays a small reviewable diff.
86
- - `maps.json` — all versions folded into one file with version ranges and interned values (≈15 KB vs ≈980 KB, and a ≈9 KB npm tarball instead of ≈19 KB). Generated automatically before tests and before packing, gitignored, and the only map that ships.
161
+ - [`maps/<package>/<version>.json`](maps) — one pretty-printed file per package version (`maps/@scope/<name>/` for scoped packages). This is the committed source of truth, so adding a version stays a small reviewable diff.
162
+ - `maps.json` — all packages and versions folded into one file with version ranges and interned values (≈140 KB for everything). Generated automatically before tests and before packing, gitignored, and the only map that ships.
87
163
 
88
164
  ```bash
89
- yarn generate-maps # fetch react-native/index.js for all versions -> maps/*.json
90
- yarn generate-maps 0.88.1 # specific versions
91
- yarn build-maps # fold maps/*.json -> maps.json (also runs on test/prepack)
165
+ yarn generate-maps # all packages, all versions -> maps/<package>/*.json
166
+ yarn generate-maps react-native-svg # one package
167
+ yarn generate-maps react-native-svg 15.16.2 # specific versions
168
+ yarn generate-maps 0.88.1 # bare versions are react-native versions
169
+ yarn build-maps # fold maps/**/*.json -> maps.json (also runs on test/prepack)
170
+ ```
171
+
172
+ `react-native` maps are read from the lazy getters of `react-native/index.js`. Every other package's maps are generated by downloading each published tarball and running the same resolver the plugin uses for unmapped packages over every name the entry exports (needs `tar`).
173
+
174
+ To add a package, create `scripts/packages/<name>.js` (`/` in a scoped name becomes `__`) and run `yarn generate-maps <name>`:
175
+
176
+ ```js
177
+ module.exports = {
178
+ name: '@scope/pkg',
179
+ minVersion: '1.0.0', // first stable release to support
180
+ extract: ['src'], // tarball folders to extract (default: src)
181
+ entry: 'src/index.ts', // entry file, when package.json points at a build
182
+ ignoreExports: true, // paths are file locations, ignoring `exports`
183
+ };
92
184
  ```
93
185
 
94
186
  ## License
package/index.js CHANGED
@@ -37,15 +37,38 @@
37
37
  *
38
38
  * Unknown names and type-only imports/exports are left untouched.
39
39
  *
40
+ * Other packages can be opted in with the `packages` option. Packages with a
41
+ * shipped map (`react-native-svg`) use the map of the installed version; any
42
+ * other package is resolved by following the ES re-exports of its installed
43
+ * entry file (see `resolve-package.js`). They stay `import` declarations:
44
+ *
45
+ * import Svg, { Defs, Path } from 'react-native-svg';
46
+ * // ->
47
+ * import Svg from 'react-native-svg/src/elements/Svg';
48
+ * import Defs from 'react-native-svg/src/elements/Defs';
49
+ * import Path from 'react-native-svg/src/elements/Path';
50
+ *
51
+ * `export { Defs } from 'pkg'` re-exports are rewritten the same way, and so is
52
+ * `require('pkg')`, all or nothing: when every usage of
53
+ * `const RNSvg = require('pkg')` is a known `RNSvg.Name` they all become inline
54
+ * `require()`s, but `fn(RNSvg)`, `RNSvg.Unknown`, `RNSvg.Name = ...`, ... keep
55
+ * the whole `require('pkg')` as it is, since it would be loaded anyway.
56
+ *
40
57
  * Options:
41
58
  * reactNativeVersion - which react-native version to generate imports for
42
59
  * (defaults to the latest known one). An unknown version falls back to the
43
60
  * closest older map, so `0.88.2` and `0.89.0` both use the `0.88.1` map.
61
+ * packages - names of other packages (besides `react-native`) to rewrite
62
+ * imports of, e.g. `['react-native-svg']`
63
+ * onModuleReexport - what to do on `module.exports = require('pkg')`:
64
+ * 'error' (default) throws, 'warn' logs and keeps the code, 'silent' keeps it
44
65
  * silenceBatchedUpdatesWarning - hides the `unstable_batchedUpdates` no-op
45
66
  * warning on 0.86+
46
67
  */
47
68
 
69
+ const fs = require('fs');
48
70
  const nodePath = require('path');
71
+ const { createPackageResolver, findPackageRoot } = require('./resolve-package');
49
72
 
50
73
  const RN = 'react-native';
51
74
 
@@ -61,9 +84,10 @@ const compareVersions = (a, b) => {
61
84
  return 0;
62
85
  };
63
86
 
64
- // `maps.json` is generated by `scripts/build-maps.js` from `maps/*.json`
65
- // (Format B: one entry per export name, with version ranges and interned
66
- // values). See that script for the exact format.
87
+ // `maps.json` is generated by `scripts/build-maps.js` from
88
+ // `maps/<package>/*.json`: one block per package (Format B: one entry per
89
+ // export name, with version ranges and interned values). See that script for
90
+ // the exact format.
67
91
  const loadData = () => require(nodePath.join(__dirname, 'maps.json'));
68
92
 
69
93
  // 'Libraries/Image/Image|default' -> ['Libraries/Image/Image', 'default']
@@ -95,18 +119,25 @@ const findMapVersion = (versions, requested) => {
95
119
  return found;
96
120
  };
97
121
 
98
- const loadMap = (version) => {
99
- const data = loadData();
122
+ // Packages with a shipped map (besides `react-native`).
123
+ const hasMap = (packageName) =>
124
+ Object.prototype.hasOwnProperty.call(loadData(), packageName);
125
+
126
+ // The map of `packageName` for `version` (default: the latest known one):
127
+ // `{ [exportName]: [pathInPackage, exportNameInModule] }`.
128
+ const loadPackageMap = (packageName, version) => {
129
+ const data = loadData()[packageName];
100
130
  const selected =
101
131
  version == null ? data.latest : findMapVersion(data.versions, version);
102
132
 
103
133
  if (selected === null) {
104
134
  throw new Error(
105
- `[react-native-direct-imports] No map for react-native ${version}. Available versions: ${data.versions.join(', ')}`,
135
+ `[react-native-direct-imports] No map for ${packageName} ${version}. Available versions: ${data.versions.join(', ')}`,
106
136
  );
107
137
  }
108
138
 
109
- const cached = resolvedMaps.get(selected);
139
+ const cacheKey = `${packageName}@${selected}`;
140
+ const cached = resolvedMaps.get(cacheKey);
110
141
  if (cached) return cached;
111
142
 
112
143
  const map = {};
@@ -118,15 +149,30 @@ const loadMap = (version) => {
118
149
  map[name] = splitValue(data.values[valueIndex]);
119
150
  }
120
151
 
121
- resolvedMaps.set(selected, map);
152
+ resolvedMaps.set(cacheKey, map);
122
153
  return map;
123
154
  };
124
155
 
156
+ const loadMap = (version) => loadPackageMap(RN, version);
157
+
125
158
  module.exports = function reactNativeDirectImports(
126
- { types: t },
127
- { reactNativeVersion, silenceBatchedUpdatesWarning = false } = {},
159
+ api,
160
+ {
161
+ reactNativeVersion,
162
+ packages = [],
163
+ onModuleReexport = 'error',
164
+ silenceBatchedUpdatesWarning = false,
165
+ } = {},
128
166
  ) {
167
+ const { types: t } = api;
168
+ if (!['error', 'warn', 'silent'].includes(onModuleReexport)) {
169
+ throw new Error(
170
+ `[react-native-direct-imports] \`onModuleReexport\` must be 'error', 'warn' or 'silent', got ${JSON.stringify(onModuleReexport)}`,
171
+ );
172
+ }
129
173
  const MAP = loadMap(reactNativeVersion);
174
+ const PACKAGES = new Set(packages);
175
+ const { resolveImport: resolveByAnalysis } = createPackageResolver(api);
130
176
 
131
177
  const buildRequire = (source, exportName) => {
132
178
  const call = t.callExpression(t.identifier('require'), [
@@ -191,8 +237,9 @@ module.exports = function reactNativeDirectImports(
191
237
  return null;
192
238
  };
193
239
 
194
- // `require('react-native')`, also wrapped in `(... as T)`, `(...)!`, `(...)`.
195
- const isRequireOfReactNative = (node, scope) => {
240
+ // `require('react-native')` or `require('<listed package>')`, also wrapped in
241
+ // `(... as T)`, `(...)!`, `(...)`. Returns the package name, or `null`.
242
+ const requiredPackage = (node, scope) => {
196
243
  while (
197
244
  t.isTSAsExpression(node) ||
198
245
  t.isTSSatisfiesExpression(node) ||
@@ -203,13 +250,17 @@ module.exports = function reactNativeDirectImports(
203
250
  ) {
204
251
  node = node.expression;
205
252
  }
206
- return (
253
+ if (
207
254
  t.isCallExpression(node) &&
208
255
  t.isIdentifier(node.callee, { name: 'require' }) &&
209
256
  !scope.hasBinding('require') &&
210
257
  node.arguments.length === 1 &&
211
- t.isStringLiteral(node.arguments[0], { value: RN })
212
- );
258
+ t.isStringLiteral(node.arguments[0]) &&
259
+ (node.arguments[0].value === RN || PACKAGES.has(node.arguments[0].value))
260
+ ) {
261
+ return node.arguments[0].value;
262
+ }
263
+ return null;
213
264
  };
214
265
 
215
266
  // Metro's `inlinePlatform` only inlines `Platform.OS` / `Platform.select`
@@ -242,25 +293,31 @@ module.exports = function reactNativeDirectImports(
242
293
  return t.identifier('Platform');
243
294
  };
244
295
 
245
- // Replaces `x.View` with the direct `require()` expression. Returns `false`
246
- // if the member can't be rewritten.
247
- const replaceMember = (memberPath, state) => {
296
+ // `x.View = ...`, `x.View++`, `delete x.View`
297
+ const isMutation = (memberPath) => {
248
298
  const { parentPath } = memberPath;
249
- if (
299
+ return (
250
300
  (parentPath.isAssignmentExpression() &&
251
301
  parentPath.node.left === memberPath.node) ||
252
302
  parentPath.isUpdateExpression() ||
253
303
  parentPath.isUnaryExpression({ operator: 'delete' })
254
- ) {
255
- return false;
256
- }
304
+ );
305
+ };
306
+
307
+ // Replaces `x.View` with the direct `require()` expression. Returns `false`
308
+ // if the member can't be rewritten. `pkg` is the package `x` was required
309
+ // from.
310
+ const replaceMember = (memberPath, state, pkg = RN) => {
311
+ if (isMutation(memberPath)) return false;
257
312
 
258
313
  const name = memberName(memberPath.node);
259
314
  const expression =
260
- (name === 'Platform' &&
261
- MAP.Platform &&
262
- platformIdentifier(memberPath, state)) ||
263
- buildDirectExpression(name);
315
+ pkg === RN
316
+ ? (name === 'Platform' &&
317
+ MAP.Platform &&
318
+ platformIdentifier(memberPath, state)) ||
319
+ buildDirectExpression(name)
320
+ : buildPackageExpression(pkg, name, state);
264
321
  if (!expression) return false;
265
322
 
266
323
  memberPath.replaceWith(expression);
@@ -320,6 +377,251 @@ module.exports = function reactNativeDirectImports(
320
377
  }
321
378
  };
322
379
 
380
+ // Whole-module re-export (`module.exports = require('pkg')`): the whole
381
+ // package ends up in the bundle, so `onModuleReexport` decides what to do.
382
+ const reportModuleReexport = (path, pkg) => {
383
+ if (onModuleReexport === 'silent') return;
384
+
385
+ const example = pkg === RN ? 'View' : 'Name';
386
+ const reason =
387
+ onModuleReexport === 'error'
388
+ ? 'is not allowed'
389
+ : 'is not rewritten and keeps the whole package in the bundle';
390
+ const error = path.buildCodeFrameError(
391
+ `\`module.exports = require('${pkg}')\` ${reason}, re-export named values instead: \`exports.${example} = require('${pkg}').${example}\``,
392
+ );
393
+ if (onModuleReexport === 'error') throw error;
394
+ console.warn(`[react-native-direct-imports] ${error.message}`);
395
+ };
396
+
397
+ // `module.exports = <ref>`
398
+ const isModuleExportsValue = (ref) => {
399
+ const { parentPath } = ref;
400
+ return (
401
+ parentPath.isAssignmentExpression() &&
402
+ parentPath.node.right === ref.node &&
403
+ parentPath.get('left').matchesPattern('module.exports')
404
+ );
405
+ };
406
+
407
+ // Packages are looked up in `node_modules` from the file being compiled.
408
+ const dirOf = (state) =>
409
+ nodePath.dirname(state.filename || nodePath.join(process.cwd(), '_'));
410
+
411
+ const installedVersions = new Map();
412
+
413
+ // Version of the package installed next to the file being compiled
414
+ // (`15.12.0-rc.1` -> `15.12.0`).
415
+ const installedVersion = (packageName, fromDir) => {
416
+ const cacheKey = `${packageName}\0${fromDir}`;
417
+ const cached = installedVersions.get(cacheKey);
418
+ if (cached) return cached;
419
+
420
+ const root = findPackageRoot(packageName, fromDir);
421
+ if (!root) {
422
+ throw new Error(
423
+ `[react-native-direct-imports] Can't find the package "${packageName}" listed in \`packages\`, looked in node_modules from ${fromDir}`,
424
+ );
425
+ }
426
+ const { version } = JSON.parse(
427
+ fs.readFileSync(nodePath.join(root, 'package.json'), 'utf8'),
428
+ );
429
+ const release = String(version).replace(/[-+].*$/, '');
430
+ installedVersions.set(cacheKey, release);
431
+ return release;
432
+ };
433
+
434
+ // `['<package>/<path>', exportName]` for `importedName` of another
435
+ // package, or `null` to keep the import. Packages with a shipped map use the
436
+ // map of the installed version; any other package is resolved by following
437
+ // the re-exports of its installed entry file.
438
+ const resolveImport = (packageName, fromDir, importedName) => {
439
+ if (!hasMap(packageName)) {
440
+ return resolveByAnalysis(packageName, fromDir, importedName);
441
+ }
442
+ const map = loadPackageMap(
443
+ packageName,
444
+ installedVersion(packageName, fromDir),
445
+ );
446
+ const entry = map[importedName];
447
+ return entry ? [`${packageName}/${entry[0]}`, entry[1]] : null;
448
+ };
449
+
450
+ // `require('<path>').<exportName>` for `importedName` of another package,
451
+ // or `null` to keep the original.
452
+ const buildPackageExpression = (pkg, importedName, state) => {
453
+ const entry =
454
+ importedName != null && resolveImport(pkg, dirOf(state), importedName);
455
+ if (!entry) return null;
456
+
457
+ const [source, exportName] = entry;
458
+ const call = buildRequire(source, '*');
459
+ if (exportName === '*') return call;
460
+ return t.isValidIdentifier(exportName, false)
461
+ ? t.memberExpression(call, t.identifier(exportName))
462
+ : t.memberExpression(call, t.stringLiteral(exportName), true);
463
+ };
464
+
465
+ // var x = require('react-native-svg');
466
+ // x.Path; x.default;
467
+ //
468
+ // Unlike `react-native`, all or nothing: if a usage can't be rewritten
469
+ // (`fn(x)`, `x.Unknown`, `x.Path = ...`, `{ ...x }`), the whole package
470
+ // stays loaded through `x` anyway, so nothing is gained by rewriting the rest.
471
+ const rewritePackageBinding = (declaratorPath, state, pkg) => {
472
+ const { name } = declaratorPath.node.id;
473
+ const binding = declaratorPath.scope.getBinding(name);
474
+ if (
475
+ !binding ||
476
+ binding.path !== declaratorPath ||
477
+ !binding.constant ||
478
+ binding.referencePaths.length === 0 ||
479
+ declaratorPath.parentPath.parentPath.isExportNamedDeclaration()
480
+ ) {
481
+ return;
482
+ }
483
+
484
+ const reexport = binding.referencePaths.find(isModuleExportsValue);
485
+ if (reexport) {
486
+ reportModuleReexport(reexport.parentPath, pkg);
487
+ return;
488
+ }
489
+
490
+ const members = [];
491
+ for (const ref of binding.referencePaths) {
492
+ const memberPath = ref.parentPath;
493
+ if (
494
+ !memberPath.isMemberExpression() ||
495
+ memberPath.node.object !== ref.node ||
496
+ isMutation(memberPath) ||
497
+ !buildPackageExpression(pkg, memberName(memberPath.node), state)
498
+ ) {
499
+ return;
500
+ }
501
+ members.push(memberPath);
502
+ }
503
+
504
+ for (const memberPath of members) replaceMember(memberPath, state, pkg);
505
+ declaratorPath.remove();
506
+ };
507
+
508
+ // const { Svg, Path: P } = require('react-native-svg');
509
+ // All or nothing too: `{ Svg, ...rest }`, `{ Unknown }`, `{ [key]: x }` and
510
+ // `{ Svg = fallback }` keep the original.
511
+ const rewritePackagePattern = (declaratorPath, state, pkg) => {
512
+ const declarators = [];
513
+
514
+ for (const prop of declaratorPath.node.id.properties) {
515
+ if (
516
+ !t.isObjectProperty(prop) ||
517
+ prop.computed ||
518
+ !t.isIdentifier(prop.value) ||
519
+ !(t.isIdentifier(prop.key) || t.isStringLiteral(prop.key))
520
+ ) {
521
+ return;
522
+ }
523
+ const expression = buildPackageExpression(pkg, nameOf(prop.key), state);
524
+ if (!expression) return;
525
+ declarators.push(t.variableDeclarator(prop.value, expression));
526
+ }
527
+
528
+ if (declarators.length > 0) declaratorPath.replaceWithMultiple(declarators);
529
+ };
530
+
531
+ // An export name as a Babel node (names like `'a-b'` are string literals).
532
+ const exportNameNode = (name) =>
533
+ t.isValidIdentifier(name, false) ? t.identifier(name) : t.stringLiteral(name);
534
+
535
+ // export { Defs, default as Svg } from 'react-native-svg';
536
+ const rewritePackageReexport = (path, state) => {
537
+ const { node } = path;
538
+ if (node.exportKind === 'type') return;
539
+
540
+ const fromDir = dirOf(state);
541
+ const kept = [];
542
+ const direct = [];
543
+
544
+ for (const spec of node.specifiers) {
545
+ const entry =
546
+ t.isExportSpecifier(spec) &&
547
+ spec.exportKind !== 'type' &&
548
+ resolveImport(node.source.value, fromDir, nameOf(spec.local));
549
+ if (!entry) {
550
+ kept.push(spec);
551
+ continue;
552
+ }
553
+
554
+ const [source, exportName] = entry;
555
+ const specifier =
556
+ exportName === '*'
557
+ ? t.exportNamespaceSpecifier(t.cloneNode(spec.exported))
558
+ : t.exportSpecifier(exportNameNode(exportName), t.cloneNode(spec.exported));
559
+ direct.push(
560
+ t.exportNamedDeclaration(null, [specifier], t.stringLiteral(source)),
561
+ );
562
+ }
563
+
564
+ if (direct.length === 0) return;
565
+
566
+ if (kept.length > 0) {
567
+ node.specifiers = kept;
568
+ path.insertAfter(direct);
569
+ } else {
570
+ path.replaceWithMultiple(direct);
571
+ }
572
+ };
573
+
574
+ // import Svg, { Defs } from 'react-native-svg';
575
+ const rewritePackageImport = (path, state) => {
576
+ const { node } = path;
577
+ if (node.importKind != null && node.importKind !== 'value') return;
578
+
579
+ const fromDir = dirOf(state);
580
+ const kept = [];
581
+ const direct = [];
582
+
583
+ for (const spec of node.specifiers) {
584
+ let imported = null;
585
+ if (t.isImportDefaultSpecifier(spec)) {
586
+ imported = 'default';
587
+ } else if (
588
+ t.isImportSpecifier(spec) &&
589
+ spec.importKind !== 'type' &&
590
+ spec.importKind !== 'typeof'
591
+ ) {
592
+ imported = nameOf(spec.imported);
593
+ }
594
+
595
+ const entry =
596
+ imported && resolveImport(node.source.value, fromDir, imported);
597
+ if (!entry) {
598
+ kept.push(spec);
599
+ continue;
600
+ }
601
+
602
+ const [source, exportName] = entry;
603
+ const local = t.identifier(spec.local.name);
604
+ let specifier;
605
+ if (exportName === 'default') {
606
+ specifier = t.importDefaultSpecifier(local);
607
+ } else if (exportName === '*') {
608
+ specifier = t.importNamespaceSpecifier(local);
609
+ } else {
610
+ specifier = t.importSpecifier(local, exportNameNode(exportName));
611
+ }
612
+ direct.push(t.importDeclaration([specifier], t.stringLiteral(source)));
613
+ }
614
+
615
+ if (direct.length === 0) return;
616
+
617
+ if (kept.length > 0) {
618
+ node.specifiers = kept;
619
+ path.insertAfter(direct);
620
+ } else {
621
+ path.replaceWithMultiple(direct);
622
+ }
623
+ };
624
+
323
625
  return {
324
626
  name: 'react-native-direct-imports',
325
627
  visitor: {
@@ -328,36 +630,38 @@ module.exports = function reactNativeDirectImports(
328
630
  // see detached paths.
329
631
  AssignmentExpression(path) {
330
632
  const { node } = path;
331
- if (
332
- path.get('left').matchesPattern('module.exports') &&
333
- isRequireOfReactNative(node.right, path.scope)
334
- ) {
335
- throw path.buildCodeFrameError(
336
- "`module.exports = require('react-native')` is not allowed, re-export named values instead: `exports.View = require('react-native').View`",
337
- );
338
- }
633
+ if (!path.get('left').matchesPattern('module.exports')) return;
634
+
635
+ const pkg = requiredPackage(node.right, path.scope);
636
+ if (pkg) reportModuleReexport(path, pkg);
339
637
  },
340
638
 
341
639
  // require('react-native').Linking
342
640
  MemberExpression(path, state) {
343
- if (isRequireOfReactNative(path.node.object, path.scope)) {
344
- replaceMember(path, state);
345
- }
641
+ const pkg = requiredPackage(path.node.object, path.scope);
642
+ if (pkg) replaceMember(path, state, pkg);
346
643
  },
347
644
 
348
645
  VariableDeclarator(path, state) {
349
646
  const { node } = path;
350
- if (!isRequireOfReactNative(node.init, path.scope)) return;
647
+ const pkg = requiredPackage(node.init, path.scope);
648
+ if (!pkg) return;
351
649
 
352
650
  if (t.isIdentifier(node.id)) {
353
- rewriteBinding(path, state);
651
+ if (pkg === RN) rewriteBinding(path, state);
652
+ else rewritePackageBinding(path, state, pkg);
354
653
  } else if (t.isObjectPattern(node.id)) {
355
- rewritePattern(path);
654
+ if (pkg === RN) rewritePattern(path);
655
+ else rewritePackagePattern(path, state, pkg);
356
656
  }
357
657
  },
358
658
 
359
- ImportDeclaration(path) {
659
+ ImportDeclaration(path, state) {
360
660
  const { node } = path;
661
+ if (node.source.value !== RN && PACKAGES.has(node.source.value)) {
662
+ rewritePackageImport(path, state);
663
+ return;
664
+ }
361
665
  if (node.source.value !== RN || node.importKind === 'type') return;
362
666
 
363
667
  if (
@@ -395,8 +699,12 @@ module.exports = function reactNativeDirectImports(
395
699
  }
396
700
  },
397
701
 
398
- ExportNamedDeclaration(path) {
702
+ ExportNamedDeclaration(path, state) {
399
703
  const { node } = path;
704
+ if (node.source && node.source.value !== RN && PACKAGES.has(node.source.value)) {
705
+ rewritePackageReexport(path, state);
706
+ return;
707
+ }
400
708
  if (node.source?.value !== RN || node.exportKind === 'type') return;
401
709
 
402
710
  const kept = [];
@@ -443,3 +751,4 @@ module.exports = function reactNativeDirectImports(
443
751
  };
444
752
 
445
753
  module.exports.loadMap = loadMap;
754
+ module.exports.loadPackageMap = loadPackageMap;