-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
115 lines (87 loc) · 2.7 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import Module from 'module';
import loaderUtils from 'loader-utils';
import validateOptions from 'schema-utils';
import schema from './options.json';
const parentModule = module;
function exec(code, loaderContext) {
const { resource, context } = loaderContext;
const module = new Module(resource, parentModule);
// eslint-disable-next-line no-underscore-dangle
module.paths = Module._nodeModulePaths(context);
module.filename = resource;
// eslint-disable-next-line no-underscore-dangle
module._compile(code, resource);
return module.exports;
}
function processResult(loaderContext, result) {
if (!result || typeof result !== 'object' || 'code' in result === false) {
loaderContext.callback(
new Error(
`The returned result of module "${loaderContext.resource}" is not an object with a "code" property`
)
);
return;
}
if (
typeof result.code !== 'string' &&
result.code instanceof Buffer === false
) {
loaderContext.callback(
new Error(
`The returned code of module "${loaderContext.resource}" is neither a string nor an instance of Buffer`
)
);
return;
}
(result.dependencies || []).forEach((dep) =>
loaderContext.addDependency(dep)
);
(result.contextDependencies || []).forEach((dep) =>
loaderContext.addContextDependency(dep)
);
// Defaults to false which is a good default here because we assume that
// results tend to be not cacheable when this loader is necessary
loaderContext.cacheable(Boolean(result.cacheable));
loaderContext.callback(
null,
result.code,
result.sourceMap || null,
result.ast || null
);
}
export default function loader(content) {
const options = loaderUtils.getOptions(this) || {};
validateOptions(schema, options, {
name: 'Val Loader',
baseDataPath: 'options',
});
let exports;
try {
exports = exec(content, this);
} catch (error) {
throw new Error(`Unable to execute "${this.resource}": ${error}`);
}
const func = exports && exports.default ? exports.default : exports;
if (typeof func !== 'function') {
throw new Error(
`Module "${this.resource}" does not export a function as default`
);
}
let result;
try {
result = func(options);
} catch (error) {
throw new Error(`Module "${this.resource}" throw error: ${error}`);
}
if (result && typeof result.then === 'function') {
const callback = this.async();
result
.then((res) => processResult(this, res))
.catch((error) => {
callback(new Error(`Module "${this.resource}" throw error: ${error}`));
});
return;
}
// No return necessary because processResult calls this.callback()
processResult(this, result);
}