fix(react): migration for babel supports configs that do not use @nx/react/babel (#30962)

This PR fixes an issue where the updated `.babelrc` is undefined if the
`@nx/react/babel` preset is missing.
This commit is contained in:
Jack Hsu 2025-04-30 22:04:27 -04:00 committed by GitHub
parent 5222a067b4
commit 8f503581b6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 2 deletions

View File

@ -50,4 +50,21 @@ describe('update-babel-loose migration', () => {
const content = tree.read(filePath, 'utf-8');
expect(content).toBe('invalid json content');
});
it('should work when @nx/react/babel is not present', async () => {
const filePath = '.babelrc';
tree.write(filePath, '{ "preset": [] } }');
await updateBabelLoose(tree);
let content = tree.read(filePath, 'utf-8');
expect(content).toMatch('{ "preset": [] } }');
tree.write(filePath, '{}');
await updateBabelLoose(tree);
content = tree.read(filePath, 'utf-8');
expect(content).toMatch('{}');
});
});

View File

@ -10,11 +10,11 @@ export default async function updateBabelLoose(tree: Tree) {
if (!path.endsWith('.babelrc')) return;
try {
updateJson(tree, path, (babelConfig) => {
if (!Array.isArray(babelConfig.presets)) return;
if (!Array.isArray(babelConfig.presets)) return babelConfig;
const ourPreset = babelConfig.presets.find(
(p) => Array.isArray(p) && p[0] === '@nx/react/babel'
);
if (!ourPreset || !ourPreset[1]) return;
if (!ourPreset || !ourPreset[1]) return babelConfig;
const options = ourPreset[1];
if (options['classProperties']?.loose !== undefined) {
options.loose = options['classProperties'].loose;