Metro adds beta Package Exports support in React Native 0.72
With React Native 0.72, Metro now includes beta support for the package.json "exports" field. According to the post, enabling it lets projects work with more npm packages out of the box, gives packages new ways to define their API and target React Native, and introduces some breaking changes to package resolution in edge cases.
Package Exports, introduced in Node.js 12.7.0, lets packages map importable subpaths to files. Its main features are package encapsulation (only listed subpaths can be imported), subpath aliases, and conditional exports that resolve differently for runtimes such as "node", "browser" or "react-native".
Enabling the beta
Apps opt in through metro.config.js:
const config = {
// ...
resolver: {
unstable_enablePackageExports: true,
},
};
Two further options control conditional exports: unstable_conditionNames (default ['require', 'import', 'react-native']) and unstable_conditionsByPlatform (by default matching 'browser' when the platform is 'web'). Imports from packages relying on "exports", such as Firebase and Storybook, should now work as designed, and React Native for Web projects using Metro can use the "browser" condition. TypeScript users can match the behaviour with moduleResolution: 'bundler' and resolvePackageJsonImports: false.
To check for resolution changes, the post suggests comparing output of yarn metro get-dependencies index.js --platform android --output before.txt and a matching after.txt run using diff before.txt after.txt.
Breaking changes and lenient encapsulation
When a package provides "exports", it is consulted first and a matched subpath target is used directly: Metro will not expand sourceExts against the import specifier, nor resolve platform-specific extensions against the target file. Subpaths not listed in "exports" fall back to legacy resolution with a warning instead of an error. A strict mode is planned for the future.
For package maintainers (preview)
Adding "exports" is optional, and there are no plans to remove support for "main" or existing resolution features. Maintainers introducing it are advised to treat it as a breaking change, and a migration guide is available in the Metro docs.
A new "react-native" community condition replaces the previous "react-native" root field. To target React Native for Web, "browser" should be listed before it. No "android" or "ios" conditions were added; Platform.select() is recommended instead.
What's next
In the next React Native release (0.73), the team aims to drop the unstable_ prefix and enable Package Exports by default for most projects.
Links
Source: reactnative.dev