-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.js
92 lines (88 loc) · 2.65 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
88
89
90
91
92
const MagicString = require("magic-string");
const {createFilter} = require("@rollup/pluginutils");
const importToGlobals = require("./lib/import-to-globals");
const defaultDynamicWrapper = id => `Promise.resolve(${id})`;
function isVirtualModule(id) {
return id.startsWith("\0");
}
function createPlugin(globals, {include, exclude, dynamicWrapper = defaultDynamicWrapper, constBindings = false} = {}) {
if (!globals) {
throw new TypeError("Missing mandatory option 'globals'");
}
let getName = globals;
const globalsType = typeof globals;
const isGlobalsObj = globalsType === "object";
if (isGlobalsObj) {
getName = function (name) {
if (Object.prototype.hasOwnProperty.call(globals, name)) {
return globals[name];
}
};
} else if (globalsType !== "function") {
throw new TypeError(`Unexpected type of 'globals', got '${globalsType}'`);
}
const dynamicWrapperType = typeof dynamicWrapper;
if (dynamicWrapperType !== "function") {
throw new TypeError(`Unexpected type of 'dynamicWrapper', got '${dynamicWrapperType}'`);
}
async function resolveId(importee, _, options) {
if (isVirtualModule(importee) || options.isEntry) return null;
const globalName = getName(importee)
return globalName ? false : null;
}
const filter = createFilter(include, exclude);
return {
name: "rollup-plugin-external-globals",
options,
transform,
};
function getDebug(context) {
return (err, message) => {
if (context.debug) {
context.debug({
message,
cause: err
});
} else if (context.warn) {
context.warn(message, err.loc ?? err.pos ?? null);
}
};
}
async function options(rawOptions) {
const plugins = Array.isArray(rawOptions.plugins)
? [...rawOptions.plugins]
: rawOptions.plugins
? [rawOptions.plugins]
: [];
plugins.unshift({
name: 'rollup-plugin-external-globals--resolver',
resolveId
});
return { ...rawOptions, plugins };
}
async function transform(code, id) {
if ((!isVirtualModule(id) && !filter(id)) || (isGlobalsObj && Object.keys(globals).every(id => !code.includes(id)))) {
return;
}
let ast;
try {
ast = this.parse(code);
} catch (err) {
getDebug(this)(err, `Failed to parse code, skip ${id}`);
return;
}
code = new MagicString(code);
const isTouched = await importToGlobals({
ast,
code,
getName,
getDynamicWrapper: dynamicWrapper,
constBindings
});
return isTouched ? {
code: code.toString(),
map: code.generateMap()
} : undefined;
}
}
module.exports = createPlugin;