Skip to content

Commit

Permalink
Fix PropTypes bug related to mixed imports and requires
Browse files Browse the repository at this point in the history
  • Loading branch information
acdlite committed Apr 14, 2017
1 parent e9c733b commit 53e723e
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 10 deletions.
24 changes: 14 additions & 10 deletions transforms/React-PropTypes-to-prop-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,23 +74,27 @@ function useVar(j, root) {
// If any PropTypes references exist, add a 'prop-types' import (or require)
function addPropTypesImport(j, root) {
if (useImportSyntax(j, root)) {
const importStatement = j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('PropTypes'))],
j.literal('prop-types')
);

const path = findImportAfterPropTypes(j, root);
if (path) {
const importStatement = j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('PropTypes'))],
j.literal('prop-types')
);
j(path).insertBefore(importStatement);
return;
}
}

j(path).insertBefore(importStatement);
} else {
const path = findRequireAfterPropTypes(j, root);
if (path) {
const requireStatement = useVar(j, root)
? j.template.statement`var PropTypes = require('prop-types');\n`
: j.template.statement`const PropTypes = require('prop-types');\n`;

const path = findRequireAfterPropTypes(j, root);

j(path.parent.parent).insertBefore(requireStatement);
return;
}

throw new Error('No PropTypes import found!');
}

// Remove PropTypes destructure statements (eg const { ProptTypes } = React)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

import type { Foo } from 'Foo';

const React = require('React');

const {PropTypes} = React;

class Component extends React.PureComponent {
render() {
return <div />;
}
}

module.exports = Component;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

import type { Foo } from 'Foo';

const PropTypes = require('prop-types');

const React = require('React');

class Component extends React.PureComponent {
render() {
return <div />;
}
}

module.exports = Component;
1 change: 1 addition & 0 deletions transforms/__tests__/React-PropTypes-to-prop-types-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const tests = [
'default-import',
'destructured-proptypes-import',
'mixed-import-and-require',
'mixed-import-and-require-2',
'named-parameters',
'no-change-import',
'no-change-require',
Expand Down

0 comments on commit 53e723e

Please sign in to comment.