UNPKG

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