-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathindex.js
75 lines (61 loc) · 2.05 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
import common from 'common-prefix';
import parsePug from './parse-pug';
import Context from './context';
import {visitExpression} from './visitors';
import {getInterpolatedTemplate} from './utils/interpolation';
import {buildJSXFragment} from './utils/jsx';
import {setBabelTypes} from './lib/babel-types';
const DEFAULT_OPTIONS = {
classAttribute: 'className',
};
export default function(babel) {
const {types: t} = babel;
setBabelTypes(t);
function isReactPugReference(node) {
// TODO: do this better
return t.isIdentifier(node, {name: 'pug'});
}
return {
visitor: {
TaggedTemplateExpression(path, state) {
const {node} = path;
const {quasis, expressions} = node.quasi;
if (isReactPugReference(node.tag) && quasis.length >= 1) {
let template, interpolationRef;
if (expressions.length) {
const interpolatedTpl = getInterpolatedTemplate(
quasis,
expressions,
);
template = interpolatedTpl.template;
interpolationRef = interpolatedTpl.interpolationRef;
} else {
template = quasis[0].value.raw;
}
let src = template.split('\n');
const minIndent = common(
src
.filter(line => line.trim() !== '')
.map(line => /^[ \t]*/.exec(line)[0]),
);
src = src.map(line => line.substr(minIndent.length)).join('\n');
const ast = parsePug(src);
const context = Context.create(this.file, path, interpolationRef, {
options: {...DEFAULT_OPTIONS, ...state.opts},
});
const transformed = ast.nodes.map(node =>
visitExpression(node, context),
);
const expression =
transformed.length === 1
? transformed[0]
: buildJSXFragment(transformed);
context.variablesToDeclare.forEach(id => {
path.scope.push({kind: 'let', id});
});
path.replaceWith(expression);
}
},
},
};
}