-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
52 lines (43 loc) · 1.21 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
'use strict';
var through = require('through2');
var acorn = require('acorn');
var falafel = require('falafel');
var regex = /(['"`])csjs\1/;
module.exports = function (file) {
if (/\.json$/.test(file)) return through();
var output = through(function(buf, enc, next) {
var source = buf.toString('utf8');
try {
var injectified = falafel(source, {
parser: acorn,
ecmaVersion: 6,
sourceType: 'module'
}, walk);
} catch (err) {
return error(err)
}
this.push(injectified.toString());
next();
});
function error(msg) {
var err = typeof msg === 'string' ? new Error(msg) : msg;
output.emit('error', err);
}
return output;
};
function walk(node){
if (node.type === 'ImportDeclaration') {
node.update(node.source().replace(regex, '$1csjs-injectify/csjs-inject$1'))
} else if (isRequire(node)) {
if (node.arguments[0].value === 'csjs') {
var quote = node.arguments[0].raw[0][0];
node.arguments[0].update(quote + 'csjs-injectify/csjs-inject' + quote);
}
}
}
function isRequire(node) {
return node.callee &&
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'require';
}