|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow |
| 8 | + * @format |
| 9 | + */ |
| 10 | + |
| 11 | +import type {CustomResolver} from 'metro-resolver'; |
| 12 | + |
| 13 | +type ResolverConfig = { |
| 14 | + platformNameMap: {[platform: string]: string}, |
| 15 | +}; |
| 16 | + |
| 17 | +/** |
| 18 | + * Creates a custom Metro resolver that maps platform extensions to package names. |
| 19 | + * To be used in app's `metro.config.js` as `resolver.resolveRequest`. |
| 20 | + */ |
| 21 | +const getPlatformResolver = (config: ResolverConfig): CustomResolver => { |
| 22 | + return (context, moduleName, platform) => { |
| 23 | + // `customResolverOptions` is populated through `?resolver.platformExtension` query params |
| 24 | + // in the jsBundleURLForBundleRoot method of the react-native/React/Base/RCTBundleURLProvider.mm |
| 25 | + const platformExtension = context.customResolverOptions?.platformExtension; |
| 26 | + let modifiedModuleName = moduleName; |
| 27 | + |
| 28 | + if ( |
| 29 | + typeof platformExtension === 'string' && |
| 30 | + config.platformNameMap?.[platformExtension] |
| 31 | + ) { |
| 32 | + const packageName = config.platformNameMap[platformExtension]; |
| 33 | + if (moduleName === 'react-native') { |
| 34 | + modifiedModuleName = packageName; |
| 35 | + } else if (moduleName.startsWith('react-native/')) { |
| 36 | + modifiedModuleName = `${packageName}/${modifiedModuleName.slice( |
| 37 | + 'react-native/'.length, |
| 38 | + )}`; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return context.resolveRequest(context, modifiedModuleName, platform); |
| 43 | + }; |
| 44 | +}; |
| 45 | + |
| 46 | +module.exports = {getPlatformResolver}; |
0 commit comments