forked from regularjs/regular-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate-rewriter.js
47 lines (40 loc) · 951 Bytes
/
template-rewriter.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
var loaderUtils = require('loader-utils');
// type if -> consequent && alternate
// type list -> body
// type element -> children
function walk( tree, fn ) {
tree.forEach(function( v ) {
if( v.type === 'element' ) {
fn( v );
if( v.children ) {
walk( v.children, fn );
}
} else if( v.type === 'if' ) {
walk( v.alternate, fn );
walk( v.consequent, fn );
} else if( v.type === 'list' ) {
walk( v.body, fn );
}
})
}
module.exports = function( content ) {
this.cacheable();
var query = loaderUtils.parseQuery( this.query );
var id = query.id;
var scoped = query.scoped;
var tree = [];
try {
tree = JSON.parse( content );
} catch( e ) {}
if( scoped ) {
walk( tree, function( node ) {
node.attrs.push({
type: 'attribute',
name: id,
value: ''
});
} );
}
// previous loaders didn't add module.exports for template, handle it here
return 'module.exports = ' + JSON.stringify( tree );
};