|
| 1 | +// reuse `@babel/types` from `metro` |
| 2 | +const metroPath = require.resolve('metro'); |
| 3 | +const babelTypesPath = require.resolve('@babel/types', { paths: [metroPath] }); |
| 4 | +const t = require(babelTypesPath); |
| 5 | + |
| 6 | +/** |
| 7 | + * Inject require('mf:init-host') right after 'use strict' directive |
| 8 | + * in React Native's Initialize Core |
| 9 | + */ |
| 10 | +function injectInitHostRequire(path, state) { |
| 11 | + // Only process once per file |
| 12 | + if (state.hasInjected) return; |
| 13 | + |
| 14 | + let insertIndex = 0; |
| 15 | + |
| 16 | + // Find the position after 'use strict' directive |
| 17 | + for (let i = 0; i < path.node.body.length; i++) { |
| 18 | + const node = path.node.body[i]; |
| 19 | + if ( |
| 20 | + t.isExpressionStatement(node) && |
| 21 | + t.isStringLiteral(node.expression) && |
| 22 | + node.expression.value === 'use strict' |
| 23 | + ) { |
| 24 | + insertIndex = i + 1; |
| 25 | + break; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // Create the require('mf:init-host') statement |
| 30 | + const requireStatement = t.expressionStatement( |
| 31 | + t.callExpression(t.identifier('require'), [t.stringLiteral('mf:init-host')]) |
| 32 | + ); |
| 33 | + |
| 34 | + // Insert the require statement |
| 35 | + path.node.body.splice(insertIndex, 0, requireStatement); |
| 36 | + state.hasInjected = true; |
| 37 | +} |
| 38 | + |
| 39 | +function metroPatchInitializeCorePlugin() { |
| 40 | + return { |
| 41 | + name: 'module-federation-metro-patch-initialize-core', |
| 42 | + visitor: { |
| 43 | + Program: { |
| 44 | + enter(_, state) { |
| 45 | + state.hasInjected = false; |
| 46 | + state.shouldTransform = state.file.opts.filename.includes( |
| 47 | + 'react-native/Libraries/Core/InitializeCore.js' |
| 48 | + ); |
| 49 | + }, |
| 50 | + exit(path, state) { |
| 51 | + if (!state.shouldTransform) return; |
| 52 | + injectInitHostRequire(path, state); |
| 53 | + }, |
| 54 | + }, |
| 55 | + }, |
| 56 | + }; |
| 57 | +} |
| 58 | + |
| 59 | +module.exports = metroPatchInitializeCorePlugin; |
0 commit comments