Skip to content

Commit 3b4b61e

Browse files
feat(NODE-4927): exports in package.json for react native and document how to polyfill for BSON (#550)
Co-authored-by: Bailey Pearson <[email protected]>
1 parent 9679ec3 commit 3b4b61e

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,40 @@ try {
309309
}
310310
```
311311

312+
## React Native
313+
314+
BSON requires that `TextEncoder`, `TextDecoder`, `atob`, `btoa`, and `crypto.getRandomValues` are available globally. These are present in most Javascript runtimes but require polyfilling in React Native. Polyfills for the missing functionality can be installed with the following command:
315+
```sh
316+
npm install --save react-native-get-random-values text-encoding-polyfill base-64
317+
```
318+
319+
The following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`.
320+
321+
```typescript
322+
// Required Polyfills For ReactNative
323+
import {encode, decode} from 'base-64';
324+
if (global.btoa == null) {
325+
global.btoa = encode;
326+
}
327+
if (global.atob == null) {
328+
global.atob = decode;
329+
}
330+
import 'text-encoding-polyfill';
331+
import 'react-native-get-random-values';
332+
```
333+
334+
Finally, import the `BSON` library like so:
335+
336+
```typescript
337+
import { BSON, EJSON } from 'bson';
338+
```
339+
340+
This will cause React Native to import the `node_modules/bson/lib/bson.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).)
341+
342+
### Technical Note about React Native module import
343+
344+
The `"exports"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/).
345+
312346
## FAQ
313347

314348
#### Why does `undefined` get converted to `null`?

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,11 @@
7575
},
7676
"main": "./lib/bson.cjs",
7777
"module": "./lib/bson.mjs",
78-
"browser": "./lib/bson.mjs",
7978
"exports": {
80-
"browser": "./lib/bson.mjs",
8179
"import": "./lib/bson.mjs",
82-
"require": "./lib/bson.cjs"
80+
"require": "./lib/bson.cjs",
81+
"react-native": "./lib/bson.cjs",
82+
"browser": "./lib/bson.mjs"
8383
},
8484
"engines": {
8585
"node": ">=14.20.1"

0 commit comments

Comments
 (0)