index.js 7.2 KB

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