UNPKG

2.15 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = _default;
7
8function _default(_ref) {
9 var t = _ref.types;
10 return {
11 visitor: {
12 Program: {
13 enter: function (path, _ref2) {
14 var file = _ref2.file;
15
16 // Do nothing if React is already declared
17 if (path.scope.hasBinding('React')) {
18 return;
19 }
20
21 var ourNode = t.importDeclaration([t.importDefaultSpecifier(t.identifier('React'))], t.stringLiteral('react')); // Add an import early, so that other plugins get to see it
22
23 file.set('ourPath', path.unshiftContainer('body', ourNode)[0]);
24 },
25 exit: function (_, _ref3) {
26 var file = _ref3.file;
27 // If our import is still intact and we haven't encountered any JSX in
28 // the program, then we just remove it. There's an edge case, where
29 // some other plugin could add JSX in its `Program.exit`, so our
30 // `JSXOpeningElement` will trigger only after this method, but it's
31 // likely that said plugin will also add a React import too.
32 var ourPath = file.get('ourPath');
33
34 if (ourPath && !file.get('hasJSX')) {
35 if (!ourPath.removed) ourPath.remove();
36 file.set('ourPath', undefined);
37 }
38 }
39 },
40 ImportDeclaration: function (path, _ref4) {
41 var file = _ref4.file;
42 // Return early if this has nothing to do with React
43 if (path.node.specifiers.every(x => x.local.name !== 'React')) return; // If our import is still intact and we encounter some other import
44 // which also imports `React`, then we remove ours.
45
46 var ourPath = file.get('ourPath');
47
48 if (ourPath && path !== ourPath) {
49 if (!ourPath.removed) ourPath.remove();
50 file.set('ourPath', undefined);
51 }
52 },
53 JSXOpeningElement: function (_, _ref5) {
54 var file = _ref5.file;
55 file.set('hasJSX', true);
56 },
57 JSXOpeningFragment: function (_, _ref6) {
58 var file = _ref6.file;
59 file.set('hasJSX', true);
60 }
61 }
62 };
63}
\No newline at end of file