index.js 8.3 KB

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