UNPKG

2.78 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4
5exports.default = function (_ref) {
6 var t = _ref.types;
7
8 function createImportDeclaration(polyfill) {
9 var declar = t.importDeclaration([], t.stringLiteral(polyfill));
10 declar._blockHoist = 3;
11 return declar;
12 }
13
14 function createRequireStatement(polyfill) {
15 return t.expressionStatement(t.callExpression(t.identifier("require"), [t.stringLiteral(polyfill)]));
16 }
17
18 function isRequire(path) {
19 return t.isExpressionStatement(path.node) && t.isCallExpression(path.node.expression) && t.isIdentifier(path.node.expression.callee) && path.node.expression.callee.name === "require" && path.node.expression.arguments.length === 1 && t.isStringLiteral(path.node.expression.arguments[0]) && isPolyfillSource(path.node.expression.arguments[0].value);
20 }
21
22 function createImport(polyfill, requireType, core) {
23 if (core) {
24 polyfill = `core-js/modules/${polyfill}`;
25 }
26
27 if (requireType === "import") {
28 return createImportDeclaration(polyfill);
29 } else {
30 return createRequireStatement(polyfill);
31 }
32 }
33
34 function createImports(polyfills, requireType, regenerator) {
35 var imports = polyfills.filter(function (el, i, arr) {
36 return arr.indexOf(el) === i;
37 }).map(function (polyfill) {
38 return createImport(polyfill, requireType, true);
39 });
40
41 return [].concat(imports, [regenerator && createImport("regenerator-runtime/runtime", requireType)]).filter(Boolean);
42 }
43
44 var isPolyfillImport = {
45 ImportDeclaration(path, state) {
46 if (path.node.specifiers.length === 0 && isPolyfillSource(path.node.source.value)) {
47 this.numPolyfillImports++;
48 if (this.numPolyfillImports > 1) {
49 path.remove();
50 return;
51 }
52
53 path.replaceWithMultiple(createImports(state.opts.polyfills, "import", state.opts.regenerator));
54 }
55 },
56 Program(path, state) {
57 var _this = this;
58
59 if (!state.opts.polyfills) {
60 throw path.buildCodeFrameError(`
61There was an issue in "babel-preset-env" such that
62the "polyfills" option was not correctly passed
63to the "transform-polyfill-require" plugin
64`);
65 }
66 path.get("body").forEach(function (bodyPath) {
67 if (isRequire(bodyPath)) {
68 _this.numPolyfillImports++;
69 if (_this.numPolyfillImports > 1) {
70 path.remove();
71 return;
72 }
73
74 bodyPath.replaceWithMultiple(createImports(state.opts.polyfills, "require", state.opts.regenerator));
75 }
76 });
77 }
78 };
79
80 return {
81 name: "transform-polyfill-require",
82 visitor: isPolyfillImport,
83 pre() {
84 this.numPolyfillImports = 0;
85 }
86 };
87};
88
89function isPolyfillSource(value) {
90 return value === "babel-polyfill" || value === "core-js";
91}
\No newline at end of file