-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformer.js
73 lines (63 loc) · 2.03 KB
/
transformer.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
'use strict'
var babel = require('picidae/exports/babel-core')
var types = babel.types
var traverse = babel.traverse
var generator = require('babel-generator').default
var errFunc = require('./lib/error-func')
function requireGenerator(varName, moduleName) {
return types.variableDeclaration('var', [
types.variableDeclarator(
types.identifier(varName),
types.callExpression(
types.identifier('require'),
[types.stringLiteral(moduleName)]
)
)
])
}
var defaultBabelConfig = require('./lib/babel-config')
module.exports = function transformer(code,
filename,
babelConfig = {}) {
var codeAst = null
try {
var ast = babel.transform(code, Object.assign({}, defaultBabelConfig, babelConfig)).ast
codeAst = ast
} catch (e) {
console.error(e)
return errFunc(e.toString())
}
var renderReturn = null
traverse(codeAst, {
CallExpression: function (callPath) {
var callPathNode = callPath.node
if (callPathNode.callee &&
callPathNode.callee.object &&
callPathNode.callee.object.name === 'ReactDOM' &&
callPathNode.callee.property &&
callPathNode.callee.property.name === 'render') {
renderReturn = types.returnStatement(
callPathNode.arguments[0]
)
callPath.remove()
}
}
})
var astProgramBody = codeAst.program.body
// if (!noreact) {
// astProgramBody.unshift(requireGenerator('ReactDOM', 'react-dom'));
// astProgramBody.unshift(requireGenerator('React', 'react'));
// }
// ReactDOM.render always at the last of preview method
if (renderReturn) {
astProgramBody.push(renderReturn)
}
var codeBlock = types.BlockStatement(astProgramBody)
// console.log(codeBlock);
var previewFunction = types.functionDeclaration(
types.Identifier('picidaeTransformerReactRender'),
[],
codeBlock
)
return generator(types.program([previewFunction]), { minified: true, filename: filename }, code).code
}