-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathes6-node-wrapper.js
76 lines (65 loc) · 2.07 KB
/
es6-node-wrapper.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
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
class ES6_Node_Wrapper {
constructor(options) {
if (arguments.length > 1) {
throw Error("ES6 Node Wrapper only takes one argument, an options object")
}
this.options = options || {};
this.set_global = options.set_global === true;
this.debug = options.debug === true;
}
wrapper(file, name, code) {
// From https://github.com/backspaces/asx/blob/master/bin/wraplibplus.js
// via https://medium.com/@backspaces/es6-modules-part-2-libs-wrap-em-up-8715e116d690
const errMsg = `wrapper failed, file: ${file} name: ${name}`;
const debugCode = this.debug
? `console.log('wraplib ${file} ${name}', {self, window, module, returnVal});`
: '';
const inWinMsg = `wrapper: window.${name} exists; exporting it.`;
name = name.replace(/-/g, '_');
const prefix = `// Programmatically created by wraplib
let result;
const win = window;
if (window.${name}) {
console.log("${inWinMsg}");
result = window.${name};
} else {
const exports = {};
const module = {};
const window = {};
const self = {};
const useGlobal = ${this.set_global};
let returnVal;
function wrap () {
returnVal =
`;
const suffix = `;
if (typeof returnVal === "boolean") returnVal = undefined;
if (!module.exports && Object.keys(exports).length > 0)
module.exports = exports;
}
wrap.call(self);
${debugCode}
result = self.${name} || window.${name} || module.exports || returnVal;
if (!result) throw Error("${errMsg}");
if (useGlobal) win.${name} = result;
}
export default result;
`;
return new ConcatSource(prefix, code, suffix);
}
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
chunks.forEach((chunk) => {
chunk.files.forEach((file) => {
compilation.assets[file] = this.wrapper(file, chunk.name, compilation.assets[file]);
});
});
callback();
});
});
}
}
module.exports = ES6_Node_Wrapper;