-
Notifications
You must be signed in to change notification settings - Fork 209
/
babel-transform-to-umd-module.js
61 lines (53 loc) · 1.52 KB
/
babel-transform-to-umd-module.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const {template, types} = require("@babel/core");
const buildWrapper = template(`
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_MODULE_NAME, ["module"], factory);
} else if (typeof exports !== "undefined") {
factory(module);
} else {
var mod = { exports: {} };
factory(mod);
global.GLOBAL = mod.exports;
}
})(
typeof globalThis !== "undefined" ? globalThis
: typeof self !== "undefined" ? self
: this,
function(module) {
}
)
`);
module.exports = (api, options = {}) => {
api.assertVersion(7);
if (typeof options.globalName != "string") {
throw new Error("globalName option is mandatory");
}
if (typeof options.amdModuleName != "string") {
throw new Error("amdModuleName is mandatory");
}
return {
name: "transform-to-umd-module",
visitor: {
Program: {
exit(path) {
const {body, directives} = path.node;
path.node.directives = [];
path.node.body = [];
const umdWrapper = path.pushContainer(
"body",
buildWrapper({
AMD_MODULE_NAME: types.stringLiteral(options.amdModuleName),
GLOBAL: options.globalName,
})
)[0];
const umdFactory = umdWrapper
.get("expression.arguments")[1]
.get("body");
umdFactory.pushContainer("directives", directives);
umdFactory.pushContainer("body", body);
},
},
},
};
};