-
Notifications
You must be signed in to change notification settings - Fork 2
/
multiple-instances-loader.js
41 lines (40 loc) · 1.18 KB
/
multiple-instances-loader.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
'use strict';
/**
* A WebPack loader to load multiple instances of a given module with differnet options and concatenate them.
*/
module.exports = function MultipleInstancesLoader(content) {
const { instances } = this.query;
if (!Array.isArray(instances)) {
throw new TypeError('Missing `instances` option.');
}
const callback = this.async();
Promise.all(
instances.map(({ loader, options }, i) => {
// eslint-disable-next-line global-require,import/no-dynamic-require
const loaderModule = typeof loader === 'string' ? require(loader) : loader;
if (typeof loaderModule !== 'function') {
throw new TypeError('Missing loader at instance#:', i);
}
return new Promise((resolve, reject) => {
loaderModule.call(
{
...this,
async() {
return (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
};
},
query: options,
},
content
);
});
})
).then(results => {
callback(null, results.join('\n'));
}, callback);
};