babel-plugin-react-native-direct-imports 1.2.1-rc.15 → 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 -161
- package/index.js +138 -51
- package/package.json +2 -2
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,204 +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`?
|
|
35
|
-
|
|
36
|
-
React Native's modules are CommonJS. If the plugin emitted `import View from '...'`, Babel's CommonJS transform would wrap every one in `_interopRequireDefault()` / `_interopRequireWildcard()` and add those helpers to each file. A plain `require(...).default` gives the same value without the extra code.
|
|
37
|
-
|
|
38
|
-
## Install
|
|
39
|
-
|
|
40
|
-
```bash
|
|
41
|
-
npm install --save-dev babel-plugin-react-native-direct-imports
|
|
42
|
-
```
|
|
29
|
+
Measure your own bundle with [react-native-bundle-discovery](https://github.com/retyui/react-native-bundle-discovery).
|
|
43
30
|
|
|
44
|
-
##
|
|
31
|
+
## Setup
|
|
45
32
|
|
|
46
|
-
|
|
47
|
-
// babel.config.js
|
|
48
|
-
module.exports = {
|
|
49
|
-
presets: [
|
|
50
|
-
// the plugin generates deep imports on purpose
|
|
51
|
-
['module:@react-native/babel-preset', { disableDeepImportWarnings: true }],
|
|
52
|
-
],
|
|
53
|
-
plugins: [
|
|
54
|
-
process.env.NODE_ENV !== 'test' && [
|
|
55
|
-
'react-native-direct-imports',
|
|
56
|
-
{ reactNativeVersion: require('react-native/package.json').version },
|
|
57
|
-
],
|
|
58
|
-
].filter(Boolean),
|
|
59
|
-
};
|
|
60
|
-
```
|
|
33
|
+
1. Install:
|
|
61
34
|
|
|
62
|
-
|
|
35
|
+
```bash
|
|
36
|
+
npm install --save-dev babel-plugin-react-native-direct-imports
|
|
37
|
+
```
|
|
63
38
|
|
|
64
|
-
|
|
39
|
+
2. Add it to `babel.config.js`:
|
|
65
40
|
|
|
66
|
-
|
|
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
|
+
```
|
|
67
56
|
|
|
68
|
-
|
|
57
|
+
3. Reset the Metro cache once: `npx react-native start --reset-cache` or `npx expo start --clear`.
|
|
69
58
|
|
|
70
|
-
|
|
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
|
-
```
|
|
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
|
-
#### Setup modules
|
|
111
|
-
|
|
112
|
-
Some entry files run **setup code** when they are loaded, which a direct import alone would skip: `react-native-reanimated` (`initializeReanimatedModule(...)`), `react-native-gesture-handler` (`initialize()` starts the native event receiver), `react-native-skia` (`NativeSetup`), `react-native-screens` (`NativeScreensModule`) and `@sentry/core` 11.x. For these, the plugin ships that code (and only that code, not the re-exports) as a small setup module per version, and imports it first in every file where it rewrites the package:
|
|
113
|
-
|
|
114
|
-
```js
|
|
115
|
-
import { useSharedValue } from 'react-native-reanimated';
|
|
116
|
-
|
|
117
|
-
// ↓ becomes
|
|
118
|
-
|
|
119
|
-
import 'babel-plugin-react-native-direct-imports/setup/react-native-reanimated/0';
|
|
120
|
-
import { useSharedValue } from 'react-native-reanimated/src/hook/useSharedValue';
|
|
121
|
-
```
|
|
63
|
+
The same works for other barrel packages. Add them to `packages`:
|
|
122
64
|
|
|
123
65
|
```js
|
|
124
|
-
|
|
125
|
-
import 'react-native-reanimated/src/publicGlobals';
|
|
126
|
-
import { initializeReanimatedModule } from 'react-native-reanimated/src/initializers';
|
|
127
|
-
import { ReanimatedModule } from 'react-native-reanimated/src/ReanimatedModule/index';
|
|
128
|
-
initializeReanimatedModule(ReanimatedModule);
|
|
66
|
+
['react-native-direct-imports', { packages: ['react-native', 'react-native-svg', 'react-native-reanimated'] }];
|
|
129
67
|
```
|
|
130
68
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
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.
|
|
134
|
-
|
|
135
|
-
### Any other package
|
|
136
|
-
|
|
137
|
-
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.
|
|
138
|
-
|
|
139
|
-
### What gets rewritten
|
|
140
|
-
|
|
141
|
-
- 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.
|
|
142
|
-
- `require('pkg')` is rewritten like it is for `react-native`, but all or nothing. These are rewritten:
|
|
143
|
-
|
|
144
|
-
```js
|
|
145
|
-
const { Svg, Path: P } = require('react-native-svg');
|
|
146
|
-
const RNSvg = require('react-native-svg');
|
|
147
|
-
RNSvg.G; RNSvg['Rect'];
|
|
148
|
-
require('react-native-svg').Circle;
|
|
149
|
-
|
|
150
|
-
// ↓ becomes
|
|
69
|
+

|
|
151
70
|
|
|
152
|
-
|
|
153
|
-
P = require('react-native-svg/src/elements/Path').default;
|
|
154
|
-
require('react-native-svg/src/elements/G').default; // each usage is a lazy inline require
|
|
155
|
-
require('react-native-svg/src/elements/Rect').default;
|
|
156
|
-
require('react-native-svg/src/elements/Circle').default;
|
|
157
|
-
```
|
|
71
|
+
Read more: [Other packages](./docs/packages.md) (versions, setup modules, what gets rewritten).
|
|
158
72
|
|
|
159
|
-
|
|
160
|
-
- `export * from 'pkg'` is not rewritten.
|
|
161
|
-
- Direct imports skip everything else the barrel does, including its side effects, except the setup of the [packages with a map](#setup-modules).
|
|
162
|
-
- 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.
|
|
73
|
+
## Good to know
|
|
163
74
|
|
|
164
|
-
|
|
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).
|
|
165
78
|
|
|
166
|
-
|
|
167
|
-
- Re-exports (`export { X } from 'react-native'`) and `require('react-native')` in compiled CommonJS code (e.g. in `node_modules`) are rewritten too.
|
|
168
|
-
- `Platform` stays a local `Platform` variable, so Metro's `Platform.OS` / `Platform.select` inlining keeps working (not for aliases like `Platform as P`).
|
|
169
|
-
- `import * as RN from 'react-native'` and `module.exports = require('react-native')` throw a build error.
|
|
170
|
-
- Generated paths point to React Native internals, which is why the map is per version.
|
|
79
|
+
## Docs
|
|
171
80
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
-
|
|
175
|
-
-
|
|
176
|
-
|
|
177
|
-
## Generating maps (development)
|
|
178
|
-
|
|
179
|
-
Each map lives in two shapes:
|
|
180
|
-
|
|
181
|
-
- [`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.
|
|
182
|
-
- `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.
|
|
183
|
-
|
|
184
|
-
```bash
|
|
185
|
-
yarn generate-maps # all packages, all versions -> maps/<package>/*.json
|
|
186
|
-
yarn generate-maps react-native-svg # one package
|
|
187
|
-
yarn generate-maps react-native-svg 15.16.2 # specific versions
|
|
188
|
-
yarn generate-maps 0.88.1 # bare versions are react-native versions
|
|
189
|
-
yarn build-maps # fold maps/**/*.json -> maps.json (also runs on test/prepack)
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
`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`).
|
|
193
|
-
|
|
194
|
-
To add a package, create `scripts/packages/<name>.js` (`/` in a scoped name becomes `__`) and run `yarn generate-maps <name>`:
|
|
195
|
-
|
|
196
|
-
```js
|
|
197
|
-
module.exports = {
|
|
198
|
-
name: '@scope/pkg',
|
|
199
|
-
minVersion: '1.0.0', // first stable release to support
|
|
200
|
-
extract: ['src'], // tarball folders to extract (default: src)
|
|
201
|
-
entry: 'src/index.ts', // entry file, when package.json points at a build
|
|
202
|
-
ignoreExports: true, // paths are file locations, ignoring `exports`
|
|
203
|
-
};
|
|
204
|
-
```
|
|
81
|
+
- [Options](./docs/options.md)
|
|
82
|
+
- [Other packages](./docs/packages.md)
|
|
83
|
+
- [Notes and compatibility](./docs/notes.md)
|
|
84
|
+
- [Generating maps](./docs/contributing.md)
|
|
205
85
|
|
|
206
86
|
## License
|
|
207
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
|
|
@@ -171,20 +172,32 @@ const SELF = require('./package.json').name;
|
|
|
171
172
|
module.exports = function reactNativeDirectImports(
|
|
172
173
|
api,
|
|
173
174
|
{
|
|
174
|
-
|
|
175
|
-
packages = [],
|
|
175
|
+
packages,
|
|
176
176
|
onModuleReexport = 'error',
|
|
177
177
|
silenceBatchedUpdatesWarning = false,
|
|
178
178
|
} = {},
|
|
179
179
|
) {
|
|
180
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
|
+
}
|
|
181
186
|
if (!['error', 'warn', 'silent'].includes(onModuleReexport)) {
|
|
182
187
|
throw new Error(
|
|
183
188
|
`[react-native-direct-imports] \`onModuleReexport\` must be 'error', 'warn' or 'silent', got ${JSON.stringify(onModuleReexport)}`,
|
|
184
189
|
);
|
|
185
190
|
}
|
|
186
|
-
|
|
187
|
-
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));
|
|
188
201
|
const { resolveImport: resolveByAnalysis } = createPackageResolver(api);
|
|
189
202
|
|
|
190
203
|
const buildRequire = (source, exportName) => {
|
|
@@ -219,7 +232,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
219
232
|
// Returns the direct `require()` expression for a name from
|
|
220
233
|
// `react-native`, or `null` if the name is not in the map.
|
|
221
234
|
const buildDirectExpression = (importedName) => {
|
|
222
|
-
const entry =
|
|
235
|
+
const entry = rnMap()[importedName];
|
|
223
236
|
if (!entry && importedName === 'unstable_batchedUpdates') {
|
|
224
237
|
return buildBatchedUpdates();
|
|
225
238
|
}
|
|
@@ -269,7 +282,8 @@ module.exports = function reactNativeDirectImports(
|
|
|
269
282
|
!scope.hasBinding('require') &&
|
|
270
283
|
node.arguments.length === 1 &&
|
|
271
284
|
t.isStringLiteral(node.arguments[0]) &&
|
|
272
|
-
(node.arguments[0].value === RN ||
|
|
285
|
+
((REWRITE_RN && node.arguments[0].value === RN) ||
|
|
286
|
+
PACKAGES.has(node.arguments[0].value))
|
|
273
287
|
) {
|
|
274
288
|
return node.arguments[0].value;
|
|
275
289
|
}
|
|
@@ -319,22 +333,24 @@ module.exports = function reactNativeDirectImports(
|
|
|
319
333
|
|
|
320
334
|
// Replaces `x.View` with the direct `require()` expression. Returns `false`
|
|
321
335
|
// if the member can't be rewritten. `pkg` is the package `x` was required
|
|
322
|
-
// from.
|
|
323
|
-
|
|
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) => {
|
|
324
339
|
if (isMutation(memberPath)) return false;
|
|
325
340
|
|
|
326
341
|
const name = memberName(memberPath.node);
|
|
327
342
|
const expression =
|
|
328
343
|
pkg === RN
|
|
329
344
|
? (name === 'Platform' &&
|
|
330
|
-
|
|
345
|
+
rnMap().Platform &&
|
|
331
346
|
platformIdentifier(memberPath, state)) ||
|
|
332
347
|
buildDirectExpression(name)
|
|
333
348
|
: buildPackageExpression(pkg, name, state);
|
|
334
349
|
if (!expression) return false;
|
|
335
350
|
|
|
336
|
-
memberPath.replaceWith(
|
|
337
|
-
|
|
351
|
+
memberPath.replaceWith(
|
|
352
|
+
inline ? withSetup(expression, state, pkg) : expression,
|
|
353
|
+
);
|
|
338
354
|
return true;
|
|
339
355
|
};
|
|
340
356
|
|
|
@@ -347,6 +363,13 @@ module.exports = function reactNativeDirectImports(
|
|
|
347
363
|
return;
|
|
348
364
|
}
|
|
349
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
|
+
|
|
350
373
|
let rewroteAll = true;
|
|
351
374
|
for (const ref of binding.referencePaths) {
|
|
352
375
|
const memberPath = ref.parentPath;
|
|
@@ -445,6 +468,24 @@ module.exports = function reactNativeDirectImports(
|
|
|
445
468
|
return release;
|
|
446
469
|
};
|
|
447
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
|
+
|
|
448
489
|
// `['<package>/<path>', exportName]` for `importedName` of another
|
|
449
490
|
// package, or `null` to keep the import. Packages with a shipped map use the
|
|
450
491
|
// map of the installed version; any other package is resolved by following
|
|
@@ -462,39 +503,78 @@ module.exports = function reactNativeDirectImports(
|
|
|
462
503
|
};
|
|
463
504
|
|
|
464
505
|
// A direct import skips what the package's entry runs on load
|
|
465
|
-
// (`initializeReanimatedModule(...)`, `initialize()`, ...), so
|
|
466
|
-
//
|
|
467
|
-
//
|
|
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:
|
|
468
509
|
//
|
|
510
|
+
// import { useSharedValue } from 'react-native-reanimated';
|
|
511
|
+
// // ->
|
|
469
512
|
// import 'babel-plugin-react-native-direct-imports/setup/react-native-reanimated/0';
|
|
513
|
+
// import { useSharedValue } from 'react-native-reanimated/src/hook/useSharedValue';
|
|
470
514
|
//
|
|
471
|
-
//
|
|
472
|
-
|
|
473
|
-
|
|
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) => {
|
|
474
543
|
state.setupAdded ??= new Set();
|
|
475
|
-
if (state.setupAdded.has(pkg)) return;
|
|
476
544
|
state.setupAdded.add(pkg);
|
|
545
|
+
};
|
|
477
546
|
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
const
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
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);
|
|
498
578
|
};
|
|
499
579
|
|
|
500
580
|
// `require('<path>').<exportName>` for `importedName` of another package,
|
|
@@ -551,6 +631,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
551
631
|
members.push(memberPath);
|
|
552
632
|
}
|
|
553
633
|
|
|
634
|
+
addSetupRequire(declaratorPath, state, pkg);
|
|
554
635
|
for (const memberPath of members) replaceMember(memberPath, state, pkg);
|
|
555
636
|
declaratorPath.remove();
|
|
556
637
|
};
|
|
@@ -576,7 +657,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
576
657
|
}
|
|
577
658
|
|
|
578
659
|
if (declarators.length === 0) return;
|
|
579
|
-
|
|
660
|
+
addSetupRequire(declaratorPath, state, pkg);
|
|
580
661
|
declaratorPath.replaceWithMultiple(declarators);
|
|
581
662
|
};
|
|
582
663
|
|
|
@@ -614,7 +695,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
614
695
|
}
|
|
615
696
|
|
|
616
697
|
if (direct.length === 0) return;
|
|
617
|
-
|
|
698
|
+
addSetupImport(path, state, node.source.value);
|
|
618
699
|
|
|
619
700
|
if (kept.length > 0) {
|
|
620
701
|
node.specifiers = kept;
|
|
@@ -666,7 +747,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
666
747
|
}
|
|
667
748
|
|
|
668
749
|
if (direct.length === 0) return;
|
|
669
|
-
|
|
750
|
+
addSetupImport(path, state, node.source.value);
|
|
670
751
|
|
|
671
752
|
if (kept.length > 0) {
|
|
672
753
|
node.specifiers = kept;
|
|
@@ -678,6 +759,12 @@ module.exports = function reactNativeDirectImports(
|
|
|
678
759
|
|
|
679
760
|
return {
|
|
680
761
|
name: 'react-native-direct-imports',
|
|
762
|
+
pre() {
|
|
763
|
+
if (REWRITE_RN) {
|
|
764
|
+
rnVersion = detectReactNativeVersion(dirOf(this));
|
|
765
|
+
MAP = null;
|
|
766
|
+
}
|
|
767
|
+
},
|
|
681
768
|
visitor: {
|
|
682
769
|
// Rewrites happen on the replaced node itself (not from the inner
|
|
683
770
|
// `require()` call), so other plugins visiting the same nodes don't
|
|
@@ -693,7 +780,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
693
780
|
// require('react-native').Linking
|
|
694
781
|
MemberExpression(path, state) {
|
|
695
782
|
const pkg = requiredPackage(path.node.object, path.scope);
|
|
696
|
-
if (pkg) replaceMember(path, state, pkg);
|
|
783
|
+
if (pkg) replaceMember(path, state, pkg, pkg !== RN);
|
|
697
784
|
},
|
|
698
785
|
|
|
699
786
|
VariableDeclarator(path, state) {
|
|
@@ -716,7 +803,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
716
803
|
rewritePackageImport(path, state);
|
|
717
804
|
return;
|
|
718
805
|
}
|
|
719
|
-
if (node.source.value !== RN || node.importKind === 'type') return;
|
|
806
|
+
if (!REWRITE_RN || node.source.value !== RN || node.importKind === 'type') return;
|
|
720
807
|
|
|
721
808
|
if (
|
|
722
809
|
node.specifiers.some((spec) => t.isImportNamespaceSpecifier(spec))
|
|
@@ -759,7 +846,7 @@ module.exports = function reactNativeDirectImports(
|
|
|
759
846
|
rewritePackageReexport(path, state);
|
|
760
847
|
return;
|
|
761
848
|
}
|
|
762
|
-
if (node.source?.value !== RN || node.exportKind === 'type') return;
|
|
849
|
+
if (!REWRITE_RN || node.source?.value !== RN || node.exportKind === 'type') return;
|
|
763
850
|
|
|
764
851
|
const kept = [];
|
|
765
852
|
const direct = [];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "babel-plugin-react-native-direct-imports",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Babel plugin that rewrites `react-native` barrel imports into direct module imports",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -54,4 +54,4 @@
|
|
|
54
54
|
"publishConfig": {
|
|
55
55
|
"access": "public"
|
|
56
56
|
}
|
|
57
|
-
}
|
|
57
|
+
}
|