-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
87 lines (80 loc) · 2.21 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const path = require("path");
const camelcase = require("lodash/camelCase");
const {transform: iifeTransform} = require("es-iife");
const IMPORT_META_URL = '(typeof document !== "undefined" && document.currentScript && document.currentScript.src || typeof location !== "undefined" && location.href || "")';
function idToName(id, nameMaps, prefix = "") {
for (const names of nameMaps) {
let name;
if (typeof names === "function") {
name = names(id);
} else if (names && typeof names === "object") {
name = names[id];
}
if (name) {
return name;
}
}
if (path.isAbsolute(id)) {
const {name} = path.parse(id);
return prefix + camelcase(name);
}
return camelcase(id);
}
function createPlugin({
sourcemap = true,
names,
prefix,
strict = true,
scriptLoader = null
} = {}) {
let isNamesResolved = false;
return {
name: "rollup-plugin-iife",
renderChunk(code, {fileName}, {dir: outputDir, globals}) {
if (!code) {
return null;
}
if (outputDir == null) {
throw new Error("failed locating output folder. Please set output.dir option");
}
if (names && typeof names === "object" && !isNamesResolved) {
const output = {};
for (const [key, value] of Object.entries(names)) {
output[resolveId(key, outputDir)] = value;
}
names = output;
isNamesResolved = true;
}
return iifeTransform({
code,
parse: this.parse,
name: idToName(path.resolve(outputDir, fileName), [names, globals], prefix),
sourcemap,
resolveGlobal: id => idToName(resolveId(id, outputDir), [names, globals], prefix),
strict
});
},
resolveImportMeta(prop, {moduleId}) {
if (prop === "url") {
return IMPORT_META_URL;
}
this.error(`Unconverted import.meta.${prop} in ${moduleId}`);
},
renderDynamicImport() {
if (!scriptLoader) {
return null;
}
return {
left: `${scriptLoader}(`,
right: `, ${IMPORT_META_URL})`
};
}
};
function resolveId(id, dir) {
if (id.startsWith(".")) {
return path.resolve(dir, id);
}
return id;
}
}
module.exports = createPlugin;