正文
"index"
:
9
}
,
"identifierName"
:
"num"
}
,
"name"
:
"num"
}
,
"init"
:
{
"type"
:
"BinaryExpression"
,
"start"
:
12
,
"end"
:
17
,
"loc"
:
{
"start"
:
{
"line"
:
1
,
"column"
:
12
,
"index"
:
12
}
,
"end"
:
{
"line"
:
1
,
"column"
:
17
,
"index"
:
17
}
}
,
"left"
:
{
"type"
:
"NumericLiteral"
,
"start"
:
12
,
"end"
:
13
,
"loc"
:
{
"start"
:
{
"line"
:
1
,
"column"
:
12
,
"index"
:
12
}
,
"end"
:
{
"line"
:
1
,
"column"
:
13
,
"index"
:
13
}
}
,
"extra"
:
{
"rawValue"
:
1
,
"raw"
:
"1"
}
,
"value"
:
1
}
,
"operator"
:
"+"
,
"right"
:
{
"type"
:
"NumericLiteral"
,
"start"
:
16
,
"end"
:
17
,
"loc"
:
{
"start"
:
{
"line"
:
1
,
"column"
:
16
,
"index"
:
16
}
,
"end"
:
{
"line"
:
1
,
"column"
:
17
,
"index"
:
17
}
}
,
"extra"
:
{
"rawValue"
:
1
,
"raw"
:
"1"
}
,
"value"
:
1
}
}
}
]
,
"kind"
:
"const"
}
]
,
"directives"
:
[
]
}
,
"comments"
:
[
]
}
上面我们实现了把代码转换为抽象语法树,下面再给大家演示一下通过抽象语法树生成代码。
安装
@babel/types
和
@babel/generator
依赖
const t =require('@babel/types');
const g =require('@babel/generator')
const ast = t.program(
[
t.variableDeclaration(
'const',
[
t.variableDeclarator(
t.identifier('num'),
t.binaryExpression(
'+',
t.numericLiteral(1),
t.numericLiteral(1)
)
)
]
)
]
)
const code = g.default(ast).code;
console.log(code);
运行上面代码后输出
二、低代码生成代码实战
1、实现思路
使用 node 起一个 express 服务,对外暴露生成代码接口,前端调用这个接口,并且把当前页面 json 数据传到后端,后端解析 json 数据生成抽象语法树,然后通过抽象语法树生成代码。
前面我实现过一个低代码 demo 项目,就拿这个项目来说吧。建议大家可以先看一下我前面做的低代码平台。
2、实战
在前端低代码页面拖一个按钮到画布,然后点击生成代码按钮,调用生成代码接口。
页面 json 数据
{
"components":[
{
"id":1,
"name":"Page",
"props":{},
"desc":"页面",
"fileName":"page",
"children":[
{
"id":1740045570763,
"fileName":"button",
"name":"Button",
"props":{
"text":{
"type":"static",
"value":"按钮"
}
},
"desc":"按钮",
"parentId":1
}
]
}
]
}
把 json 数据转换为 jsx 元素
const t =require('@babel/types');
const g =require('@babel/generator')
const prettier =require('prettier');
functioncreateJsxStatement(component){
// 创建 jsx 元素
return t.jsxElement(
t.jsxOpeningElement(
t.jsxIdentifier(component.name),
[