Fix build for Reactotron plugin

Summary: Fixed build for Reactotron plugin. It was broken because one of dependencies has statement "import * as React from 'react'" which transformed wrongly.

Reviewed By: passy

Differential Revision: D21178313

fbshipit-source-id: d700981a570dc8ded2080910e872b44976b850e8
This commit is contained in:
Anton Nikolaev
2020-04-22 09:24:39 -07:00
committed by Facebook GitHub Bot
parent 2890306ad5
commit 1a692ccf08
3 changed files with 17 additions and 2 deletions

View File

@@ -50,6 +50,14 @@ test('transform React identifier to global.React', () => {
expect(code).toBe('global.React;');
});
test('do NOT transform local React namespace import to global.React', () => {
const src = `import * as React from 'react';`;
const ast = parse(src, {sourceType: 'module'});
const transformed = transformFromAstSync(ast, src, babelOptions)!.ast;
const {code} = generate(transformed!);
expect(code).toMatchInlineSnapshot(`"import * as React from 'react';"`);
});
test('throw error when requiring outside the plugin', () => {
const src = 'require("../test.js")';
const ast = parse(src);

View File

@@ -31,6 +31,12 @@ function isExcludedPath(path: string) {
}
return false;
}
function isReactImportIdentifier(path: NodePath<Identifier>) {
return (
path.parentPath.node.type === 'ImportNamespaceSpecifier' &&
path.parentPath.node.local.name === 'React'
);
}
module.exports = () => ({
visitor: {
CallExpression(path: NodePath<CallExpression>, state: any) {
@@ -80,6 +86,7 @@ module.exports = () => ({
if (
path.node.name === 'React' &&
(path.parentPath.node as any).id !== path.node &&
!isReactImportIdentifier(path) &&
!isExcludedPath(state.file.opts.filename)
) {
path.replaceWith(identifier('global.React'));

View File

@@ -20,8 +20,8 @@ export default function transform({
filename: string;
options: any;
src: string;
presets: any[];
plugins: any[];
presets?: any[];
plugins?: any[];
}) {
presets = presets ?? [require('@babel/preset-react')];
plugins = plugins ?? [];