Skip to content

Commit

Permalink
Prevent Babel registration from transforming plugins with arbitrary c…
Browse files Browse the repository at this point in the history
…onfig

Summary:
X-link: facebook/react-native#39429

Using `require` after `const registerFn = require('babel/register')` but before `registerFn(config)` causes Babel to transform required code with the default configuration (ie, using a nearby `babel.config.js`, if available).

This was causing the Babel plugins loaded by `metro-babel-register` to be (unnecessarily) transformed according to `babel.config.js`, which actually fails if the plugins/presets referenced in `babel.config.js` themselves require transformation.

This ensures no code is loaded in between registering Babel as a side effect of requiring Babel register, and replacing that hook with something explicitly configured.

## React Native
Changelog: [Internal]

## Metro
```
* **[Fix]:** `metro-babel-register` prevent arbitrary transformation of Babel plugins during registration setup
```

Reviewed By: dmytrorykun

Differential Revision: D49238671

fbshipit-source-id: 52a55b1b5dbd127171558c056f16ab04e8fa8232
  • Loading branch information
robhogan authored and facebook-github-bot committed Sep 14, 2023
1 parent e0dd91b commit e8f468d
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/metro-babel-register/src/babel-register.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,18 @@ const path = require('path');
let _only /*: $ReadOnlyArray<RegExp | string> */ = [];

function register(onlyList /*: $ReadOnlyArray<RegExp | string> */) {
require('@babel/register')({
// NB: `require('@babel/register')` registers Babel as a side-effect, and
// also returns a register function that overrides the first registration
// when called.
//
// If `require` is used between the two registrations, Babel will behave in
// its default mode, searching for a config file and loading whatever
// plugins/presets are specified within, to compile whatever is `require`d.
//
// Since our `config()` uses `require` to load plugins, and we don't want
// these plugins to be compiled with an arbitrary Babel config, we must
// prepare the config object before calling `require('@babel/register')`.
const registerConfig = {
...config(onlyList),
extensions: [
'.ts',
Expand All @@ -34,7 +45,9 @@ function register(onlyList /*: $ReadOnlyArray<RegExp | string> */) {
'.js',
'.mjs',
],
});
};

require('@babel/register')(registerConfig);
}

function config(
Expand Down

0 comments on commit e8f468d

Please sign in to comment.