Use metro-babel-register for additive Babel registration (#45295)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45295

When registering Babel to run RN from source, we currently call `babel/register` directly from `scripts/babel-register.js`.

This has the effect of overwriting any previous registration, which causes problems in the FB monorepo because RN also loads other projects that lie outside this registration (like Metro) from source - possibly requiring different configurations.

Moreover, if Metro is subsequently loaded from source, its own registration clobbers RN's.

Instead, this diff runs the registration through `metro-babel-register`, which maintains a cumulative list of registration directories and applies a uniform transform.

Note that this means we're not using exactly the same transform at build/publish time as for running from source - to fix that, we ought to move everything to a central `babel.config.js`, but that's a much bigger change, and this gets us close enough to unblock.

Changelog: [Internal]

Reviewed By: hoxyq

Differential Revision: D59376984

fbshipit-source-id: 0dbb00970ac87dbe40ec8904bf51ef4b1fee5e0f
This commit is contained in:
Rob Hogan 2024-07-05 04:48:30 -07:00 committed by Facebook GitHub Bot
parent 42f1adf49f
commit 06fc6f2beb

View File

@ -10,8 +10,6 @@
*/
const {PACKAGES_DIR} = require('./build');
const {buildConfig, getBabelConfig} = require('./config');
const path = require('path');
let isRegisteredForMonorepo = false;
@ -32,28 +30,9 @@ function registerForMonorepo() {
return;
}
for (const [packageName, {target}] of Object.entries(buildConfig.packages)) {
if (target === 'node') {
registerPackage(packageName);
}
}
require('metro-babel-register')([PACKAGES_DIR]);
isRegisteredForMonorepo = true;
}
function registerPackage(packageName /*: string */) {
const packageDir = path.join(PACKAGES_DIR, packageName);
// Prepare the config object before calling `require('@babel/register')` to
// prevent `require` calls within `getBabelConfig` triggering Babel to
// attempt to load its config from a babel.config file.
const registerConfig = {
...getBabelConfig(packageName),
root: packageDir,
ignore: [/[/\\]node_modules[/\\]/],
};
require('@babel/register')(registerConfig);
}
module.exports = {registerForMonorepo};