index.js 8.1 KB

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