Each file in this directory loads one optional React Native dependency (a peer dependency the app may not have installed) and tells the rest of the SDK whether it is available.
The shims are not bundled into the main SDK bundle. Rolldown builds each one to the same path under dist/import.react_native/, and the main React Native bundles require it by relative path (see rolldown.config.mjs). The rest of this section explains why.
-
Every file in an app's bundle is a module with a numeric ID.
-
When Metro transforms a module, each
require('some-package')becomes a local index. Metro lists the module'srequires in order of appearance and rewrites each one to_$$_REQUIRE(_dependencyMap[i]). These indices are fixed at transform time, before Metro checks whether the packages are installed. -
When Metro writes the bundle, it gives each module a dependency map. That's an array mapping local index → module ID, passed as an argument to the module's definition:
// the module's code, as transformed: _$$_REQUIRE(_dependencyMap[16], "fast-text-encoding") _$$_REQUIRE(_dependencyMap[17], "react-native-get-random-values") // the module's definition in the bundle: id 538, then its dependency map __d(function (...) { /* module code */ }, 538, [76, 27, /* ... */, 541, 547, 556], "…/index.react_native.min.js");
A require inside try/catch is an optional dependency, as long as the app's Metro config has allowOptionalDependencies on (React Native's and Expo's defaults turn it on). If the package isn't installed, Metro doesn't fail the build.
Metro 0.82.4 and older also removes the missing dependency from the module's dependency map, so the array closes the gap. The module's code still uses the original indices, so every require after the missing one shifts by one.
This used to hit the SDK when all of its React Native code was one Rollup bundle, meaning one Metro module. Its dependency map ended with:
| Index | Dependency |
|---|---|
| 14 | @react-native-async-storage/async-storage (optional) |
| 15 | @react-native-community/netinfo |
| 16 | fast-text-encoding (optional) |
| 17 | react-native-get-random-values (optional) |
With fast-text-encoding not installed, index 16 got react-native-get-random-values's module ID and index 17 pointed past the end of the array:
require("fast-text-encoding")silently loadedreact-native-get-random-values. No error was thrown, noTextEncoderwas set up, and decisions failed later.require("react-native-get-random-values")becamerequire(undefined), which throws "Requiring unknown module". The SDK then reported "install react-native-get-random-values" even though that package was installed.- A missing async-storage would have shifted netinfo and both polyfill
requires.
How require(undefined) fails also depends on timing:
- While a module is loading: the error is thrown to the caller, so a
try/catcharound therequirecatches it. - Any other time (for example a
requireinside a function called later): Metro's loader catches the error itself and reports it as a fatal error. That's a red box in dev and usually a crash in release. The caller'scatchnever sees it.
Metro 0.82.5 fixed the bug by keeping a null placeholder for a missing dependency. Requiring null throws "Cannot find module", wherever it happens.
Who's affected: apps on React Native 0.78 or older, and on 0.79 or 0.80 if their Metro is below 0.82.5. Apps with every optional package installed aren't affected, because nothing gets removed.
- Each optional
requireis alone in its own module. A shim's dependency map has a single entry: its package. If the package is missing, the map is empty and therequirebecomesrequire(undefined). There is no otherrequirein the module that could shift. - Each shim does its
requirewhile the module loads. Therequire(undefined)error is then thrown to the shim'stry/catch, which setsisAvailable = false. On Metro 0.82.5 and later therequirethrows "Cannot find module", with the same result. - The main bundle loads shims by relative path, for example
require("./import.react_native/fast-text-encoding.js"). Those files always exist, so the main bundle's dependency map never has a missing entry, and none of itsrequires can shift.
The rules below keep those guarantees.
Two optional requires in one module could shift each other, as described above, so each optional package gets its own shim. The file path is the package name plus .ts. A scoped package goes in a folder named after its scope.
| Package | Shim |
|---|---|
fast-text-encoding |
fast-text-encoding.ts |
react-native-get-random-values |
react-native-get-random-values.ts |
@react-native-async-storage/async-storage |
@react-native-async-storage/async-storage.ts |
A test goes next to its shim as <name>.spec.ts. Spec files are not built as shims.
isAvailable:trueif the package loaded,falseif itsrequirethrew.- The package's exports, under the same names: if the package isn't installed they are
undefined. A shim may adapt a value as long as it keeps the package's shape. For example, the async-storage shim addsmultiGeton AsyncStorage v3. - Only the exports the SDK uses: this isn't required for correctness. Re-exporting more would still be one
require. It just keeps the shims small. - Packages loaded only for side effects: polyfills like
fast-text-encodingonly needisAvailable. - A shim can use
export defaultwhen the package has a default export, as the async-storage shim does:- Shims are built as CommonJS. A default export becomes
exports.default, and the file is marked with__esModule. - In the main CJS bundles, Rolldown wraps a
requireof an external CommonJS module in its__toESMhelper, which readsexports.defaultfor a default import when the module is marked with__esModule.import AsyncStorage from '…/async-storage'therefore gets the storage, not the shim's exports object. (Rollup neededinterop: 'esModule'for this; Rolldown needs no setting.) - Shims are only built as CommonJS; the ESM main bundle imports the same CommonJS files. The app's bundler (Metro, or webpack) reads
exports.defaultfor a default import from a CommonJS module marked with__esModule.
- Shims are built as CommonJS. A default export becomes
- Never throw. A shim catches the
requireerror, setsisAvailable = false, and leaves its exportsundefined. The importer decides what a missing package means. For example,index.react_native.tsthrows ifTextEncoderis still missing after the polyfill shims run, andAsyncStorageCachethrows "Module not found" when there's no AsyncStorage.
The optional require must be the only require in the built shim (dist/import.react_native/<name>.js). Any other require in the module could shift when the optional package is missing.
The build enforces this. The rn-import-shim-check plugin in rolldown.config.mjs fails the build if a built shim contains any require other than its own package's. The package is taken from the shim's name, so the check also enforces the naming convention.
-
Wrap the
requiredirectly intry/catch. Metro only treats arequireas optional when it is directly inside atryblock. Without that, a missing package fails the app's build. -
Run it at module load, not later in a function. Only then is a failed
requirethrown to the shim'scatch. Later, Metro before 0.82.5 reports it as a fatal error instead (see "The bug in Metro before 0.82.5"). -
Type-only imports are fine. TypeScript removes them, for example
import { Platform } from '../platform_support'. -
No other runtime imports, not even of guaranteed packages. Each of these adds a
requireto the built shim:- A package import, even of a regular dependency, stays a
requirein the shim. It would only be safe if Metro listed it before the optionalrequirein the shim's dependency map, and Metro's inline requires move imports around, so that order can't be relied on. - SDK code imported by more than one shim goes into a shared file that each of them
requires.
SDK code imported by only one shim is copied into it and adds no
require, so the check allows it. It is a separate copy from the one in the main bundle, though, so any module state is not shared. Keep shims self-contained. - A package import, even of a regular dependency, stays a
-
No syntax that needs
tslibhelpers. With the repo's ES6 target,async/awaitcompiles to atslib__awaiterimport, which adds arequire('tslib'). Use.then()instead. -
Export
__platforms, as every file inlib/does for the platform-isolation check.
import { Platform } from '../platform_support';
export let isAvailable = true;
// Only the exports the SDK uses, under the package's names.
export let someExport: SomeType | undefined;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
someExport = require('some-package').someExport;
} catch (e) {
isAvailable = false;
}
export const __platforms: Platform[] = ['react_native'];Importers use a shim through a normal relative import, for example import { isAvailable, someExport } from './import.react_native/some-package'. The rn-import-shim-external plugin in rolldown.config.mjs turns that into the relative require of the built shim.