-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
42 lines (33 loc) · 1.01 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
const babel = require('@babel/core');
module.exports = () => ({
visitor: {
Program: {
enter: (path, state) => {
const opts = state.opts || {};
const file = state.file || {};
if (!opts || !opts.prepend) {
throw new Error('The prepend option is missing');
}
if (typeof opts.accept !== 'undefined' && typeof opts.accept !== 'function') {
throw new Error('The accept option must be a function');
}
if (opts.accept && !opts.accept(file.opts.filename)) {
return;
}
let parsed = null;
try {
parsed = babel.parse(opts.prepend, { filename: '' });
} catch (e) {
throw new Error('Error parsing prepend value: ' + opts.prepend);
}
if (!parsed || !parsed.program || !parsed.program.body) {
throw new Error('Error parsing prepend value: ' + opts.prepend);
}
if (parsed.program.body.length > 1) {
throw new Error('The prepend value must contain one single statement');
}
path.node.body.unshift(parsed.program.body[0]);
}
}
}
});