jsx-pragma.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. var _pluginSyntaxJsx = _interopRequireDefault(require("next/dist/compiled/babel/plugin-syntax-jsx"));
  7. function _interopRequireDefault(obj) {
  8. return obj && obj.__esModule ? obj : {
  9. default: obj
  10. };
  11. }
  12. function _default({ types: t }) {
  13. return {
  14. inherits: _pluginSyntaxJsx.default,
  15. visitor: {
  16. JSXElement (_path, state) {
  17. state.set("jsx", true);
  18. },
  19. // Fragment syntax is still JSX since it compiles to createElement(),
  20. // but JSXFragment is not a JSXElement
  21. JSXFragment (_path, state) {
  22. state.set("jsx", true);
  23. },
  24. Program: {
  25. exit (path, state) {
  26. if (state.get("jsx")) {
  27. const pragma = t.identifier(state.opts.pragma);
  28. let importAs = pragma;
  29. // if there's already a React in scope, use that instead of adding an import
  30. const existingBinding = state.opts.reuseImport !== false && state.opts.importAs && path.scope.getBinding(state.opts.importAs);
  31. // var _jsx = _pragma.createElement;
  32. if (state.opts.property) {
  33. if (state.opts.importAs) {
  34. importAs = t.identifier(state.opts.importAs);
  35. } else {
  36. importAs = path.scope.generateUidIdentifier("pragma");
  37. }
  38. const mapping = t.variableDeclaration("var", [
  39. t.variableDeclarator(pragma, t.memberExpression(importAs, t.identifier(state.opts.property))),
  40. ]);
  41. // if the React binding came from a require('react'),
  42. // make sure that our usage comes after it.
  43. let newPath;
  44. if (existingBinding && t.isVariableDeclarator(existingBinding.path.node) && t.isCallExpression(existingBinding.path.node.init) && t.isIdentifier(existingBinding.path.node.init.callee) && existingBinding.path.node.init.callee.name === "require") {
  45. [newPath] = existingBinding.path.parentPath.insertAfter(mapping);
  46. } else {
  47. [newPath] = path.unshiftContainer("body", mapping);
  48. }
  49. for (const declar of newPath.get("declarations")){
  50. path.scope.registerBinding(newPath.node.kind, declar);
  51. }
  52. }
  53. if (!existingBinding) {
  54. const importSpecifier = t.importDeclaration([
  55. state.opts.import ? t.importSpecifier(importAs, t.identifier(state.opts.import)) : state.opts.importNamespace ? t.importNamespaceSpecifier(importAs) : t.importDefaultSpecifier(importAs),
  56. ], t.stringLiteral(state.opts.module || "react"));
  57. const [newPath] = path.unshiftContainer("body", importSpecifier);
  58. for (const specifier of newPath.get("specifiers")){
  59. path.scope.registerBinding("module", specifier);
  60. }
  61. }
  62. }
  63. }
  64. }
  65. }
  66. };
  67. }
  68. //# sourceMappingURL=jsx-pragma.js.map