babel-plugin-react-native-direct-imports 1.2.1-rc.14 → 2.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/CHANGELOG.md +68 -0
- package/README.md +41 -141
- package/index.js +163 -21
- package/maps.json +1 -1
- package/package.json +4 -3
- package/resolve-package.js +180 -19
- package/setup/@sentry/core/0.js +4 -0
- package/setup/react-native-gesture-handler/0.js +4 -0
- package/setup/react-native-gesture-handler/1.js +5 -0
- package/setup/react-native-reanimated/0.js +6 -0
- package/setup/react-native-screens/0.js +3 -0
- package/setup/react-native-skia/0.js +3 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# babel-plugin-react-native-direct-imports
|
|
2
|
+
|
|
3
|
+
## 2.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- [#12](https://github.com/retyui/babel-plugin-react-native-direct-imports/pull/12) [`2a99f5f`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/2a99f5ffd1b2c7b6a37007208c4e2c04c73237b1) Thanks [@retyui](https://github.com/retyui)! - `packages` is now required, and `react-native` is rewritten only when it is listed there, so you choose what gets optimized:
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
['react-native-direct-imports', { packages: ['react-native', 'react-native-svg'] }];
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Without `packages` the plugin throws. To keep the old behavior, add `{ packages: ['react-native'] }`.
|
|
14
|
+
|
|
15
|
+
The `reactNativeVersion` option is removed: the plugin reads the installed `react-native` version (looked up from each compiled file), like it does for the other packages. If `react-native` can't be found, the latest known map is used. Remove `reactNativeVersion` from your config.
|
|
16
|
+
|
|
17
|
+
### Minor Changes
|
|
18
|
+
|
|
19
|
+
- [#12](https://github.com/retyui/babel-plugin-react-native-direct-imports/pull/12) [`7922889`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/7922889c87027f6ba6afda58577b5d5a58d80c01) Thanks [@retyui](https://github.com/retyui)! - Ship maps for more packages, so listing them in `packages` needs no other config:
|
|
20
|
+
|
|
21
|
+
- `react-native-reanimated` `4.0.0`+, `react-native-gesture-handler` `2.0.0`+, `react-native-screens` `4.0.0`+, `react-native-skia` `3.0.0`+, `react-native-keyboard-controller` `1.20.0`+, `react-native-notify-kit` `10.0.0`+ and `@gorhom/bottom-sheet` `5.0.0`+ (`src/...` paths)
|
|
22
|
+
- `@sentry/core` `10.0.0`+ (`build/esm/...`) and `@sentry/react-native` `7.0.0`+ (`dist/js/...`)
|
|
23
|
+
|
|
24
|
+
Packages whose entry runs setup code on load (Reanimated's `initializeReanimatedModule`, Gesture Handler's `initialize()`, Skia's `NativeSetup`, Screens' `NativeScreensModule`) now ship a small setup module per version. The plugin imports it first in every file where it rewrites that package, so direct imports no longer skip the setup (this fixes `Cannot convert undefined value to object` in Reanimated's `processViewUpdates`).
|
|
25
|
+
|
|
26
|
+
Adding a package is now a config file in `scripts/packages/`.
|
|
27
|
+
|
|
28
|
+
- [#10](https://github.com/retyui/babel-plugin-react-native-direct-imports/pull/10) [`9f5c4f0`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/9f5c4f0f00d7c8f2cd768b463a0bf093c7c98e81) Thanks [@retyui](https://github.com/retyui)! - Add a `packages` option to rewrite barrel imports of other packages, not only `react-native`:
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
['react-native-direct-imports', { packages: ['react-native-svg'] }];
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import Svg, { Defs, Path } from 'react-native-svg';
|
|
36
|
+
// ->
|
|
37
|
+
import Svg from 'react-native-svg/src/elements/Svg';
|
|
38
|
+
import Defs from 'react-native-svg/src/elements/Defs';
|
|
39
|
+
import Path from 'react-native-svg/src/elements/Path';
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`export { ... } from 'pkg'` re-exports are rewritten too, and so is `require('pkg')` (`const { Svg } = require('pkg')`, `const X = require('pkg'); X.Path`, `require('pkg').Path`), all or nothing: a binding that is passed around, mutated or uses an unknown name keeps its original `require`.
|
|
43
|
+
|
|
44
|
+
New `onModuleReexport` option (`'error'` by default, or `'warn'` / `'silent'`) controls `module.exports = require('react-native')` and the same for listed packages.
|
|
45
|
+
|
|
46
|
+
`react-native-svg` (`15.0.0` and newer) ships a map per version, picked from the installed version like `react-native`'s. Any other package listed in `packages` is resolved by following the ES re-exports of its installed entry file to the module that defines each name. A package's `exports` field is honored, both for the entry and for aliases: the emitted path is the public subpath a file is exposed as, and files `exports` doesn't expose are left alone.
|
|
47
|
+
|
|
48
|
+
The per-version source maps moved from `maps/<version>.json` to `maps/<package>/<version>.json`, and `maps.json` is now keyed by package.
|
|
49
|
+
|
|
50
|
+
## 1.2.0
|
|
51
|
+
|
|
52
|
+
### Minor Changes
|
|
53
|
+
|
|
54
|
+
- [#8](https://github.com/retyui/babel-plugin-react-native-direct-imports/pull/8) [`a4c6d6e`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/a4c6d6e76448742134745b8c11e9a2ac0aff06f4) Thanks [@retyui](https://github.com/retyui)! - Ship all version maps as a single `maps.json` with version ranges instead of 142 per-version files, cutting the installed package size by ~98% (≈980 KB of maps -> ≈15 KB) and the npm tarball from ≈19 KB to ≈10 KB.
|
|
55
|
+
|
|
56
|
+
An unknown `reactNativeVersion` now falls back to the closest older map instead of failing the build, so upgrading React Native before updating the plugin no longer breaks it. Only a version older than every known map (< 0.70.0) throws.
|
|
57
|
+
|
|
58
|
+
## 1.1.2
|
|
59
|
+
|
|
60
|
+
### Patch Changes
|
|
61
|
+
|
|
62
|
+
- [`2570f1a`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/2570f1acf12e7d79f827fb4ad240bfd850e7ebf9) Thanks [@retyui](https://github.com/retyui)! - Add react-native 0.88.1 map
|
|
63
|
+
|
|
64
|
+
## 1.1.1
|
|
65
|
+
|
|
66
|
+
### Patch Changes
|
|
67
|
+
|
|
68
|
+
- [`cc962c5`](https://github.com/retyui/babel-plugin-react-native-direct-imports/commit/cc962c50b402247d6fce371fe1a8afc2dd429ca3) Thanks [@retyui](https://github.com/retyui)! - Publish via npm trusted publishing with provenance
|
package/README.md
CHANGED
|
@@ -4,184 +4,84 @@
|
|
|
4
4
|
[](https://www.npmtrends.com/babel-plugin-react-native-direct-imports)
|
|
5
5
|
[](https://www.npmjs.com/package/babel-plugin-react-native-direct-imports)
|
|
6
6
|
|
|
7
|
-
Babel plugin that
|
|
7
|
+
Babel plugin that turns barrel imports (`react-native`, `react-native-svg`, ...) into direct imports of the modules you use, so only those end up in the bundle.
|
|
8
8
|
|
|
9
9
|
> [!WARNING]
|
|
10
|
-
>
|
|
10
|
+
> Early stage. Expect rough edges and breaking changes, and please [report issues](https://github.com/retyui/babel-plugin-react-native-direct-imports/issues).
|
|
11
11
|
|
|
12
12
|

|
|
13
13
|
|
|
14
14
|
```js
|
|
15
|
-
import { View, AppRegistry
|
|
15
|
+
import { View, AppRegistry } from 'react-native';
|
|
16
16
|
|
|
17
17
|
// ↓ becomes
|
|
18
18
|
|
|
19
19
|
const View = require('react-native/Libraries/Components/View/View').default;
|
|
20
20
|
const AppRegistry = require('react-native/Libraries/ReactNative/AppRegistry').AppRegistry;
|
|
21
|
-
const Systrace = require('react-native/Libraries/Performance/Systrace');
|
|
22
21
|
```
|
|
23
22
|
|
|
24
23
|
## Why
|
|
25
24
|
|
|
26
|
-
`react-native/index.js` is a
|
|
27
|
-
|
|
28
|
-
Bundle with only `import { ReactNativeVersion } from 'react-native'`, before and after:
|
|
25
|
+
`react-native/index.js` is a barrel with a lazy getter for every public API. Metro can't tree-shake it, so one `import { View } from 'react-native'` pulls in all of React Native.
|
|
29
26
|
|
|
30
27
|

|
|
31
28
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
### Why `require()` and not `import`?
|
|
29
|
+
Measure your own bundle with [react-native-bundle-discovery](https://github.com/retyui/react-native-bundle-discovery).
|
|
35
30
|
|
|
36
|
-
|
|
31
|
+
## Setup
|
|
37
32
|
|
|
38
|
-
|
|
33
|
+
1. Install:
|
|
39
34
|
|
|
40
|
-
```bash
|
|
41
|
-
npm install --save-dev babel-plugin-react-native-direct-imports
|
|
42
|
-
```
|
|
35
|
+
```bash
|
|
36
|
+
npm install --save-dev babel-plugin-react-native-direct-imports
|
|
37
|
+
```
|
|
43
38
|
|
|
44
|
-
|
|
39
|
+
2. Add it to `babel.config.js`:
|
|
45
40
|
|
|
46
|
-
```js
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
};
|
|
60
|
-
```
|
|
41
|
+
```js
|
|
42
|
+
module.exports = {
|
|
43
|
+
presets: [
|
|
44
|
+
// the plugin generates deep imports on purpose
|
|
45
|
+
['module:@react-native/babel-preset', { disableDeepImportWarnings: true }],
|
|
46
|
+
],
|
|
47
|
+
plugins: [
|
|
48
|
+
process.env.NODE_ENV !== 'test' && [
|
|
49
|
+
'react-native-direct-imports',
|
|
50
|
+
// required: only the packages listed here are rewritten
|
|
51
|
+
{ packages: ['react-native'] },
|
|
52
|
+
],
|
|
53
|
+
].filter(Boolean),
|
|
54
|
+
};
|
|
55
|
+
```
|
|
61
56
|
|
|
62
|
-
|
|
57
|
+
3. Reset the Metro cache once: `npx react-native start --reset-cache` or `npx expo start --clear`.
|
|
63
58
|
|
|
64
|
-
|
|
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
|
-
|
|
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.
|
|
59
|
+
The installed React Native version is detected automatically. See [all options](./docs/options.md).
|
|
71
60
|
|
|
72
61
|
## Other packages
|
|
73
62
|
|
|
74
|
-
The same
|
|
75
|
-
|
|
76
|
-
```js
|
|
77
|
-
['react-native-direct-imports', { packages: ['react-native-svg'] }];
|
|
78
|
-
```
|
|
63
|
+
The same works for other barrel packages. Add them to `packages`:
|
|
79
64
|
|
|
80
65
|
```js
|
|
81
|
-
|
|
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';
|
|
66
|
+
['react-native-direct-imports', { packages: ['react-native', 'react-native-svg', 'react-native-reanimated'] }];
|
|
91
67
|
```
|
|
92
68
|
|
|
93
|
-
|
|
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.
|
|
69
|
+

|
|
143
70
|
|
|
144
|
-
|
|
71
|
+
Read more: [Other packages](./docs/packages.md) (versions, setup modules, what gets rewritten).
|
|
145
72
|
|
|
146
|
-
|
|
147
|
-
- Re-exports (`export { X } from 'react-native'`) and `require('react-native')` in compiled CommonJS code (e.g. in `node_modules`) are rewritten too.
|
|
148
|
-
- `Platform` stays a local `Platform` variable, so Metro's `Platform.OS` / `Platform.select` inlining keeps working (not for aliases like `Platform as P`).
|
|
149
|
-
- `import * as RN from 'react-native'` and `module.exports = require('react-native')` throw a build error.
|
|
150
|
-
- Generated paths point to React Native internals, which is why the map is per version.
|
|
73
|
+
## Good to know
|
|
151
74
|
|
|
152
|
-
|
|
75
|
+
- With `react-native` listed, `import * as RN from 'react-native'` and `module.exports = require('react-native')` fail the build.
|
|
76
|
+
- `@sentry/*` deep paths need Metro package exports off. See [details](./docs/packages.md#packages-with-a-map).
|
|
77
|
+
- On `react-native-worklets` bundle mode, use `0.14.0` or newer. See [compatibility](./docs/notes.md#compatibility).
|
|
153
78
|
|
|
154
|
-
|
|
155
|
-
- ⚠️ `react-native-worklets` bundle mode: before `0.14.0`, `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 on `react-native-worklets` < `0.14.0`; upgrade to `0.14.0` or newer.
|
|
79
|
+
## Docs
|
|
156
80
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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.
|
|
163
|
-
|
|
164
|
-
```bash
|
|
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
|
-
};
|
|
184
|
-
```
|
|
81
|
+
- [Options](./docs/options.md)
|
|
82
|
+
- [Other packages](./docs/packages.md)
|
|
83
|
+
- [Notes and compatibility](./docs/notes.md)
|
|
84
|
+
- [Generating maps](./docs/contributing.md)
|
|
185
85
|
|
|
186
86
|
## License
|
|
187
87
|
|
package/index.js
CHANGED
|
@@ -37,8 +37,8 @@
|
|
|
37
37
|
*
|
|
38
38
|
* Unknown names and type-only imports/exports are left untouched.
|
|
39
39
|
*
|
|
40
|
-
*
|
|
41
|
-
* shipped map (`react-native-svg`) use the map of the installed version; any
|
|
40
|
+
* Each package, `react-native` included, is opted in with the `packages` option. Packages with a
|
|
41
|
+
* shipped map (`maps/`: `react-native-svg`, `react-native-reanimated`, ...) use the map of the installed version; any
|
|
42
42
|
* other package is resolved by following the ES re-exports of its installed
|
|
43
43
|
* entry file (see `resolve-package.js`). They stay `import` declarations:
|
|
44
44
|
*
|
|
@@ -48,6 +48,9 @@
|
|
|
48
48
|
* import Defs from 'react-native-svg/src/elements/Defs';
|
|
49
49
|
* import Path from 'react-native-svg/src/elements/Path';
|
|
50
50
|
*
|
|
51
|
+
* Packages whose entry runs code on load (`react-native-reanimated`, ...) also
|
|
52
|
+
* get their setup module imported where the package used to load (see `setupSource`).
|
|
53
|
+
*
|
|
51
54
|
* `export { Defs } from 'pkg'` re-exports are rewritten the same way, and so is
|
|
52
55
|
* `require('pkg')`, all or nothing: when every usage of
|
|
53
56
|
* `const RNSvg = require('pkg')` is a known `RNSvg.Name` they all become inline
|
|
@@ -55,11 +58,9 @@
|
|
|
55
58
|
* the whole `require('pkg')` as it is, since it would be loaded anyway.
|
|
56
59
|
*
|
|
57
60
|
* Options:
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
* packages - names of other packages (besides `react-native`) to rewrite
|
|
62
|
-
* imports of, e.g. `['react-native-svg']`
|
|
61
|
+
* packages (required) - names of the packages to rewrite imports of, e.g.
|
|
62
|
+
* `['react-native', 'react-native-svg']`; `react-native` too is only
|
|
63
|
+
* rewritten when listed
|
|
63
64
|
* onModuleReexport - what to do on `module.exports = require('pkg')`:
|
|
64
65
|
* 'error' (default) throws, 'warn' logs and keeps the code, 'silent' keeps it
|
|
65
66
|
* silenceBatchedUpdatesWarning - hides the `unstable_batchedUpdates` no-op
|
|
@@ -155,23 +156,48 @@ const loadPackageMap = (packageName, version) => {
|
|
|
155
156
|
|
|
156
157
|
const loadMap = (version) => loadPackageMap(RN, version);
|
|
157
158
|
|
|
159
|
+
// Index of the setup module (`setup/<package>/<index>.js`, written by
|
|
160
|
+
// `scripts/build-maps.js`) of `packageName`'s map for `version`, or `null`
|
|
161
|
+
// when its entry runs nothing on load.
|
|
162
|
+
const loadPackageSetup = (packageName, version) => {
|
|
163
|
+
const data = loadData()[packageName];
|
|
164
|
+
const selected =
|
|
165
|
+
version == null ? data.latest : findMapVersion(data.versions, version);
|
|
166
|
+
if (selected === null || !data.setup) return null;
|
|
167
|
+
return pickWindow(data.setup, selected);
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const SELF = require('./package.json').name;
|
|
171
|
+
|
|
158
172
|
module.exports = function reactNativeDirectImports(
|
|
159
173
|
api,
|
|
160
174
|
{
|
|
161
|
-
|
|
162
|
-
packages = [],
|
|
175
|
+
packages,
|
|
163
176
|
onModuleReexport = 'error',
|
|
164
177
|
silenceBatchedUpdatesWarning = false,
|
|
165
178
|
} = {},
|
|
166
179
|
) {
|
|
167
180
|
const { types: t } = api;
|
|
181
|
+
if (!Array.isArray(packages)) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
`[react-native-direct-imports] \`packages\` is required: list the packages to rewrite imports of, e.g. { packages: ['react-native', 'react-native-svg'] }`,
|
|
184
|
+
);
|
|
185
|
+
}
|
|
168
186
|
if (!['error', 'warn', 'silent'].includes(onModuleReexport)) {
|
|
169
187
|
throw new Error(
|
|
170
188
|
`[react-native-direct-imports] \`onModuleReexport\` must be 'error', 'warn' or 'silent', got ${JSON.stringify(onModuleReexport)}`,
|
|
171
189
|
);
|
|
172
190
|
}
|
|
173
|
-
|
|
174
|
-
const
|
|
191
|
+
// `react-native` is only rewritten when it is listed in `packages`.
|
|
192
|
+
const REWRITE_RN = packages.includes(RN);
|
|
193
|
+
// The react-native version of the file being compiled, set in `pre()`: the
|
|
194
|
+
// version installed next to the file (like the other packages), or `null`
|
|
195
|
+
// (the latest known map) when it isn't installed. Its map is loaded on the
|
|
196
|
+
// first react-native import, so files that don't import it never fail.
|
|
197
|
+
let rnVersion = null;
|
|
198
|
+
let MAP = null;
|
|
199
|
+
const rnMap = () => (MAP ??= loadMap(rnVersion));
|
|
200
|
+
const PACKAGES = new Set(packages.filter((name) => name !== RN));
|
|
175
201
|
const { resolveImport: resolveByAnalysis } = createPackageResolver(api);
|
|
176
202
|
|
|
177
203
|
const buildRequire = (source, exportName) => {
|
|
@@ -206,7 +232,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
206
232
|
// Returns the direct `require()` expression for a name from
|
|
207
233
|
// `react-native`, or `null` if the name is not in the map.
|
|
208
234
|
const buildDirectExpression = (importedName) => {
|
|
209
|
-
const entry =
|
|
235
|
+
const entry = rnMap()[importedName];
|
|
210
236
|
if (!entry && importedName === 'unstable_batchedUpdates') {
|
|
211
237
|
return buildBatchedUpdates();
|
|
212
238
|
}
|
|
@@ -256,7 +282,8 @@ module.exports = function reactNativeDirectImports(
|
|
|
256
282
|
!scope.hasBinding('require') &&
|
|
257
283
|
node.arguments.length === 1 &&
|
|
258
284
|
t.isStringLiteral(node.arguments[0]) &&
|
|
259
|
-
(node.arguments[0].value === RN ||
|
|
285
|
+
((REWRITE_RN && node.arguments[0].value === RN) ||
|
|
286
|
+
PACKAGES.has(node.arguments[0].value))
|
|
260
287
|
) {
|
|
261
288
|
return node.arguments[0].value;
|
|
262
289
|
}
|
|
@@ -306,21 +333,24 @@ module.exports = function reactNativeDirectImports(
|
|
|
306
333
|
|
|
307
334
|
// Replaces `x.View` with the direct `require()` expression. Returns `false`
|
|
308
335
|
// if the member can't be rewritten. `pkg` is the package `x` was required
|
|
309
|
-
// from.
|
|
310
|
-
|
|
336
|
+
// from. `inline` is set for `require('pkg').Name`, which gets the setup of
|
|
337
|
+
// `pkg` where it is evaluated.
|
|
338
|
+
const replaceMember = (memberPath, state, pkg = RN, inline = false) => {
|
|
311
339
|
if (isMutation(memberPath)) return false;
|
|
312
340
|
|
|
313
341
|
const name = memberName(memberPath.node);
|
|
314
342
|
const expression =
|
|
315
343
|
pkg === RN
|
|
316
344
|
? (name === 'Platform' &&
|
|
317
|
-
|
|
345
|
+
rnMap().Platform &&
|
|
318
346
|
platformIdentifier(memberPath, state)) ||
|
|
319
347
|
buildDirectExpression(name)
|
|
320
348
|
: buildPackageExpression(pkg, name, state);
|
|
321
349
|
if (!expression) return false;
|
|
322
350
|
|
|
323
|
-
memberPath.replaceWith(
|
|
351
|
+
memberPath.replaceWith(
|
|
352
|
+
inline ? withSetup(expression, state, pkg) : expression,
|
|
353
|
+
);
|
|
324
354
|
return true;
|
|
325
355
|
};
|
|
326
356
|
|
|
@@ -333,6 +363,13 @@ module.exports = function reactNativeDirectImports(
|
|
|
333
363
|
return;
|
|
334
364
|
}
|
|
335
365
|
|
|
366
|
+
// const x = require('react-native'); module.exports = x;
|
|
367
|
+
const reexport = binding.referencePaths.find(isModuleExportsValue);
|
|
368
|
+
if (reexport) {
|
|
369
|
+
reportModuleReexport(reexport.parentPath, RN);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
336
373
|
let rewroteAll = true;
|
|
337
374
|
for (const ref of binding.referencePaths) {
|
|
338
375
|
const memberPath = ref.parentPath;
|
|
@@ -431,6 +468,24 @@ module.exports = function reactNativeDirectImports(
|
|
|
431
468
|
return release;
|
|
432
469
|
};
|
|
433
470
|
|
|
471
|
+
// Version of `react-native` installed next to the file being compiled, or
|
|
472
|
+
// `null` (the latest map) when it can't be found. Nightlies
|
|
473
|
+
// (`0.0.0-<date>-<sha>`) are built from main, so they use the latest map too.
|
|
474
|
+
const detectReactNativeVersion = (fromDir) => {
|
|
475
|
+
const cacheKey = `${RN}\0${fromDir}`;
|
|
476
|
+
if (installedVersions.has(cacheKey)) return installedVersions.get(cacheKey);
|
|
477
|
+
const root = findPackageRoot(RN, fromDir);
|
|
478
|
+
let version = root
|
|
479
|
+
? String(
|
|
480
|
+
JSON.parse(fs.readFileSync(nodePath.join(root, 'package.json'), 'utf8'))
|
|
481
|
+
.version,
|
|
482
|
+
).replace(/[-+].*/, '')
|
|
483
|
+
: null;
|
|
484
|
+
if (version === '0.0.0') version = null;
|
|
485
|
+
installedVersions.set(cacheKey, version);
|
|
486
|
+
return version;
|
|
487
|
+
};
|
|
488
|
+
|
|
434
489
|
// `['<package>/<path>', exportName]` for `importedName` of another
|
|
435
490
|
// package, or `null` to keep the import. Packages with a shipped map use the
|
|
436
491
|
// map of the installed version; any other package is resolved by following
|
|
@@ -447,6 +502,81 @@ module.exports = function reactNativeDirectImports(
|
|
|
447
502
|
return entry ? [`${packageName}/${entry[0]}`, entry[1]] : null;
|
|
448
503
|
};
|
|
449
504
|
|
|
505
|
+
// A direct import skips what the package's entry runs on load
|
|
506
|
+
// (`initializeReanimatedModule(...)`, `initialize()`, ...), so rewrites of
|
|
507
|
+
// a package with setup add its setup module where the package used to load.
|
|
508
|
+
// Modules are cached, so the setup runs once per app:
|
|
509
|
+
//
|
|
510
|
+
// import { useSharedValue } from 'react-native-reanimated';
|
|
511
|
+
// // ->
|
|
512
|
+
// import 'babel-plugin-react-native-direct-imports/setup/react-native-reanimated/0';
|
|
513
|
+
// import { useSharedValue } from 'react-native-reanimated/src/hook/useSharedValue';
|
|
514
|
+
//
|
|
515
|
+
// `import`/`export ... from` get an `import` right before them (imports
|
|
516
|
+
// above it, like polyfills, still run first). `require()` keeps its
|
|
517
|
+
// evaluation site, so a conditional or lazy `require('pkg')` only runs the
|
|
518
|
+
// setup when it runs:
|
|
519
|
+
//
|
|
520
|
+
// const G = require('pkg'); -> require('<setup>'); const G = ...;
|
|
521
|
+
// if (c) require('pkg').X; -> if (c) (require('<setup>'), require('pkg/x')).X;
|
|
522
|
+
//
|
|
523
|
+
// Once a setup runs unconditionally at the top level of the file, later
|
|
524
|
+
// rewrites of the same package in it don't add another.
|
|
525
|
+
|
|
526
|
+
// The setup module of `pkg` for the file being compiled, or `null`.
|
|
527
|
+
const setupSource = (state, pkg) => {
|
|
528
|
+
if (!hasMap(pkg)) return null;
|
|
529
|
+
state.setupSources ??= new Map();
|
|
530
|
+
if (!state.setupSources.has(pkg)) {
|
|
531
|
+
const index = loadPackageSetup(pkg, installedVersion(pkg, dirOf(state)));
|
|
532
|
+
state.setupSources.set(
|
|
533
|
+
pkg,
|
|
534
|
+
index === null ? null : `${SELF}/setup/${pkg}/${index}`,
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
return state.setupSources.get(pkg);
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
// Whether the setup of `pkg` already runs unconditionally above `path`.
|
|
541
|
+
const hasTopLevelSetup = (state, pkg) => state.setupAdded?.has(pkg) ?? false;
|
|
542
|
+
const markTopLevelSetup = (state, pkg) => {
|
|
543
|
+
state.setupAdded ??= new Set();
|
|
544
|
+
state.setupAdded.add(pkg);
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
const requireSetup = (source) =>
|
|
548
|
+
t.callExpression(t.identifier('require'), [t.stringLiteral(source)]);
|
|
549
|
+
|
|
550
|
+
// `import`/`export ... from 'pkg'` (always top-level).
|
|
551
|
+
const addSetupImport = (path, state, pkg) => {
|
|
552
|
+
const source = setupSource(state, pkg);
|
|
553
|
+
if (source === null || hasTopLevelSetup(state, pkg)) return;
|
|
554
|
+
markTopLevelSetup(state, pkg);
|
|
555
|
+
path.insertBefore(t.importDeclaration([], t.stringLiteral(source)));
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
// `const ... = require('pkg')`: before its declaration.
|
|
559
|
+
const addSetupRequire = (declaratorPath, state, pkg) => {
|
|
560
|
+
const source = setupSource(state, pkg);
|
|
561
|
+
if (source === null || hasTopLevelSetup(state, pkg)) return;
|
|
562
|
+
const statement = declaratorPath.getStatementParent();
|
|
563
|
+
if (statement.parentPath.isProgram()) markTopLevelSetup(state, pkg);
|
|
564
|
+
statement.insertBefore(t.expressionStatement(requireSetup(source)));
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
// `require('pkg').Name` -> `(require('<setup>'), require('pkg/x')).Name`
|
|
568
|
+
const withSetup = (expression, state, pkg) => {
|
|
569
|
+
const source = setupSource(state, pkg);
|
|
570
|
+
if (source === null || hasTopLevelSetup(state, pkg)) return expression;
|
|
571
|
+
const wrap = (call) => t.sequenceExpression([requireSetup(source), call]);
|
|
572
|
+
if (t.isMemberExpression(expression)) {
|
|
573
|
+
// Wrapping the object keeps `this` of `require('pkg').fn()`.
|
|
574
|
+
expression.object = wrap(expression.object);
|
|
575
|
+
return expression;
|
|
576
|
+
}
|
|
577
|
+
return wrap(expression);
|
|
578
|
+
};
|
|
579
|
+
|
|
450
580
|
// `require('<path>').<exportName>` for `importedName` of another package,
|
|
451
581
|
// or `null` to keep the original.
|
|
452
582
|
const buildPackageExpression = (pkg, importedName, state) => {
|
|
@@ -501,6 +631,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
501
631
|
members.push(memberPath);
|
|
502
632
|
}
|
|
503
633
|
|
|
634
|
+
addSetupRequire(declaratorPath, state, pkg);
|
|
504
635
|
for (const memberPath of members) replaceMember(memberPath, state, pkg);
|
|
505
636
|
declaratorPath.remove();
|
|
506
637
|
};
|
|
@@ -525,7 +656,9 @@ module.exports = function reactNativeDirectImports(
|
|
|
525
656
|
declarators.push(t.variableDeclarator(prop.value, expression));
|
|
526
657
|
}
|
|
527
658
|
|
|
528
|
-
if (declarators.length
|
|
659
|
+
if (declarators.length === 0) return;
|
|
660
|
+
addSetupRequire(declaratorPath, state, pkg);
|
|
661
|
+
declaratorPath.replaceWithMultiple(declarators);
|
|
529
662
|
};
|
|
530
663
|
|
|
531
664
|
// An export name as a Babel node (names like `'a-b'` are string literals).
|
|
@@ -562,6 +695,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
562
695
|
}
|
|
563
696
|
|
|
564
697
|
if (direct.length === 0) return;
|
|
698
|
+
addSetupImport(path, state, node.source.value);
|
|
565
699
|
|
|
566
700
|
if (kept.length > 0) {
|
|
567
701
|
node.specifiers = kept;
|
|
@@ -613,6 +747,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
613
747
|
}
|
|
614
748
|
|
|
615
749
|
if (direct.length === 0) return;
|
|
750
|
+
addSetupImport(path, state, node.source.value);
|
|
616
751
|
|
|
617
752
|
if (kept.length > 0) {
|
|
618
753
|
node.specifiers = kept;
|
|
@@ -624,6 +759,12 @@ module.exports = function reactNativeDirectImports(
|
|
|
624
759
|
|
|
625
760
|
return {
|
|
626
761
|
name: 'react-native-direct-imports',
|
|
762
|
+
pre() {
|
|
763
|
+
if (REWRITE_RN) {
|
|
764
|
+
rnVersion = detectReactNativeVersion(dirOf(this));
|
|
765
|
+
MAP = null;
|
|
766
|
+
}
|
|
767
|
+
},
|
|
627
768
|
visitor: {
|
|
628
769
|
// Rewrites happen on the replaced node itself (not from the inner
|
|
629
770
|
// `require()` call), so other plugins visiting the same nodes don't
|
|
@@ -639,7 +780,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
639
780
|
// require('react-native').Linking
|
|
640
781
|
MemberExpression(path, state) {
|
|
641
782
|
const pkg = requiredPackage(path.node.object, path.scope);
|
|
642
|
-
if (pkg) replaceMember(path, state, pkg);
|
|
783
|
+
if (pkg) replaceMember(path, state, pkg, pkg !== RN);
|
|
643
784
|
},
|
|
644
785
|
|
|
645
786
|
VariableDeclarator(path, state) {
|
|
@@ -662,7 +803,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
662
803
|
rewritePackageImport(path, state);
|
|
663
804
|
return;
|
|
664
805
|
}
|
|
665
|
-
if (node.source.value !== RN || node.importKind === 'type') return;
|
|
806
|
+
if (!REWRITE_RN || node.source.value !== RN || node.importKind === 'type') return;
|
|
666
807
|
|
|
667
808
|
if (
|
|
668
809
|
node.specifiers.some((spec) => t.isImportNamespaceSpecifier(spec))
|
|
@@ -705,7 +846,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
705
846
|
rewritePackageReexport(path, state);
|
|
706
847
|
return;
|
|
707
848
|
}
|
|
708
|
-
if (node.source?.value !== RN || node.exportKind === 'type') return;
|
|
849
|
+
if (!REWRITE_RN || node.source?.value !== RN || node.exportKind === 'type') return;
|
|
709
850
|
|
|
710
851
|
const kept = [];
|
|
711
852
|
const direct = [];
|
|
@@ -752,3 +893,4 @@ module.exports = function reactNativeDirectImports(
|
|
|
752
893
|
|
|
753
894
|
module.exports.loadMap = loadMap;
|
|
754
895
|
module.exports.loadPackageMap = loadPackageMap;
|
|
896
|
+
module.exports.loadPackageSetup = loadPackageSetup;
|