index.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _helperModuleTransforms = require("@babel/helper-module-transforms");
  8. var _helperSimpleAccess = require("@babel/helper-simple-access");
  9. var _core = require("@babel/core");
  10. var _utils = require("babel-plugin-dynamic-import-node/utils");
  11. var _default = (0, _helperPluginUtils.declare)((api, options) => {
  12. var _api$assumption, _api$assumption2;
  13. api.assertVersion(7);
  14. const transformImportCall = (0, _utils.createDynamicImportTransform)(api);
  15. const {
  16. strictNamespace = false,
  17. mjsStrictNamespace = true,
  18. allowTopLevelThis,
  19. strict,
  20. strictMode,
  21. noInterop,
  22. importInterop,
  23. lazy = false,
  24. allowCommonJSExports = true
  25. } = options;
  26. const constantReexports = (_api$assumption = api.assumption("constantReexports")) != null ? _api$assumption : options.loose;
  27. const enumerableModuleMeta = (_api$assumption2 = api.assumption("enumerableModuleMeta")) != null ? _api$assumption2 : options.loose;
  28. if (typeof lazy !== "boolean" && typeof lazy !== "function" && (!Array.isArray(lazy) || !lazy.every(item => typeof item === "string"))) {
  29. throw new Error(`.lazy must be a boolean, array of strings, or a function`);
  30. }
  31. if (typeof strictNamespace !== "boolean") {
  32. throw new Error(`.strictNamespace must be a boolean, or undefined`);
  33. }
  34. if (typeof mjsStrictNamespace !== "boolean") {
  35. throw new Error(`.mjsStrictNamespace must be a boolean, or undefined`);
  36. }
  37. const getAssertion = localName => _core.template.expression.ast`
  38. (function(){
  39. throw new Error(
  40. "The CommonJS '" + "${localName}" + "' variable is not available in ES6 modules." +
  41. "Consider setting setting sourceType:script or sourceType:unambiguous in your " +
  42. "Babel config for this file.");
  43. })()
  44. `;
  45. const moduleExportsVisitor = {
  46. ReferencedIdentifier(path) {
  47. const localName = path.node.name;
  48. if (localName !== "module" && localName !== "exports") return;
  49. const localBinding = path.scope.getBinding(localName);
  50. const rootBinding = this.scope.getBinding(localName);
  51. if (rootBinding !== localBinding || path.parentPath.isObjectProperty({
  52. value: path.node
  53. }) && path.parentPath.parentPath.isObjectPattern() || path.parentPath.isAssignmentExpression({
  54. left: path.node
  55. }) || path.isAssignmentExpression({
  56. left: path.node
  57. })) {
  58. return;
  59. }
  60. path.replaceWith(getAssertion(localName));
  61. },
  62. AssignmentExpression(path) {
  63. const left = path.get("left");
  64. if (left.isIdentifier()) {
  65. const localName = path.node.name;
  66. if (localName !== "module" && localName !== "exports") return;
  67. const localBinding = path.scope.getBinding(localName);
  68. const rootBinding = this.scope.getBinding(localName);
  69. if (rootBinding !== localBinding) return;
  70. const right = path.get("right");
  71. right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
  72. } else if (left.isPattern()) {
  73. const ids = left.getOuterBindingIdentifiers();
  74. const localName = Object.keys(ids).filter(localName => {
  75. if (localName !== "module" && localName !== "exports") return false;
  76. return this.scope.getBinding(localName) === path.scope.getBinding(localName);
  77. })[0];
  78. if (localName) {
  79. const right = path.get("right");
  80. right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
  81. }
  82. }
  83. }
  84. };
  85. return {
  86. name: "transform-modules-commonjs",
  87. pre() {
  88. this.file.set("@babel/plugin-transform-modules-*", "commonjs");
  89. },
  90. visitor: {
  91. CallExpression(path) {
  92. if (!this.file.has("@babel/plugin-proposal-dynamic-import")) return;
  93. if (!path.get("callee").isImport()) return;
  94. let {
  95. scope
  96. } = path;
  97. do {
  98. scope.rename("require");
  99. } while (scope = scope.parent);
  100. transformImportCall(this, path.get("callee"));
  101. },
  102. Program: {
  103. exit(path, state) {
  104. if (!(0, _helperModuleTransforms.isModule)(path)) return;
  105. path.scope.rename("exports");
  106. path.scope.rename("module");
  107. path.scope.rename("require");
  108. path.scope.rename("__filename");
  109. path.scope.rename("__dirname");
  110. if (!allowCommonJSExports) {
  111. (0, _helperSimpleAccess.default)(path, new Set(["module", "exports"]));
  112. path.traverse(moduleExportsVisitor, {
  113. scope: path.scope
  114. });
  115. }
  116. let moduleName = (0, _helperModuleTransforms.getModuleName)(this.file.opts, options);
  117. if (moduleName) moduleName = _core.types.stringLiteral(moduleName);
  118. const {
  119. meta,
  120. headers
  121. } = (0, _helperModuleTransforms.rewriteModuleStatementsAndPrepareHeader)(path, {
  122. exportName: "exports",
  123. constantReexports,
  124. enumerableModuleMeta,
  125. strict,
  126. strictMode,
  127. allowTopLevelThis,
  128. noInterop,
  129. importInterop,
  130. lazy,
  131. esNamespaceOnly: typeof state.filename === "string" && /\.mjs$/.test(state.filename) ? mjsStrictNamespace : strictNamespace
  132. });
  133. for (const [source, metadata] of meta.source) {
  134. const loadExpr = _core.types.callExpression(_core.types.identifier("require"), [_core.types.stringLiteral(source)]);
  135. let header;
  136. if ((0, _helperModuleTransforms.isSideEffectImport)(metadata)) {
  137. if (metadata.lazy) throw new Error("Assertion failure");
  138. header = _core.types.expressionStatement(loadExpr);
  139. } else {
  140. const init = (0, _helperModuleTransforms.wrapInterop)(path, loadExpr, metadata.interop) || loadExpr;
  141. if (metadata.lazy) {
  142. header = _core.template.ast`
  143. function ${metadata.name}() {
  144. const data = ${init};
  145. ${metadata.name} = function(){ return data; };
  146. return data;
  147. }
  148. `;
  149. } else {
  150. header = _core.template.ast`
  151. var ${metadata.name} = ${init};
  152. `;
  153. }
  154. }
  155. header.loc = metadata.loc;
  156. headers.push(header);
  157. headers.push(...(0, _helperModuleTransforms.buildNamespaceInitStatements)(meta, metadata, constantReexports));
  158. }
  159. (0, _helperModuleTransforms.ensureStatementsHoisted)(headers);
  160. path.unshiftContainer("body", headers);
  161. }
  162. }
  163. }
  164. };
  165. });
  166. exports.default = _default;