# 十一.seal
1.转换箭头函数
//是babel的核心库
let babel = require("@babel/core")
//生成节点
let t = require("babel-types")
let code = `const sum=(a,b)+>a+b`
let transformArrayFunction = {
//访问器模式 访问者
visitor: {
ArrayFunctionExpression: (path, state) => {
let node = path.node //拿到路径里的节点
let id = path.parent.id //path.parent父节点的意思
let params = node.params
// let body = node.body;//BinaryExprssion
let body = t.blockStatement([t.returnStatement(node.body)])
let functionDeclaration = t.functionDeclaration(
id,
params,
body,
false,
false
)
path.parentath.replaceWith(functionDeclaration)
},
},
}
let result = babel.transform(core, {
plugins: [transformArrayFunction],
})
console.log(result.code)
console.log("result", result)
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
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
2.把类转换
let transformArrowFunctions = {
visitor: {
ClassDeclaration: (path, state) => {
let node = path.node;
let id = node.id;
let methods = node.body.body;
let functions = [];
methods.forEach(function(method) {
if (method.kind == "constructor") {
let func = t.functionDeclaration(
id,
method.params,
method.body,
false,
false
);
} else {let memberExpression=t.memberExpression(t.memberExpression(id,t.identifier('protype'))
let memberFunciton = t.functionDeclaration(
null,
method.params,
method.body,
false,
false
);
t.assignmentExpression("=", memberExpression, memberFunciton);
statment.push(assignmentExpression);
}
});
}
}
};
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
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