Skip to content

Commit

Permalink
feat: 对class转换插件优化
Browse files Browse the repository at this point in the history
  • Loading branch information
okbug committed Nov 20, 2021
1 parent 986180a commit 945c7d9
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions learnWebpack/ast-demo/3.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,15 @@ class A {
}
getName() {
console.log(name)
return this.name
}
setName(newName) {
console.log(newName);
if (newName === this.name) return;
this.name = name;
}
}
`

Expand All @@ -23,18 +30,18 @@ let res2 = core.transform(code2, {
const myClassTransformPlugin = {
visitor: {
ClassDeclaration(nodePath) {
// console.log(nodePath)
let {node} = nodePath;
let {id} = node;
let body = []
let classMethods = node.body.body; // 方法: constructor, getName
let classMethods = node.body.body; // 方法: constructor, getName等等
classMethods.forEach(method => {
if (method.kind === 'construcotr') { // 构造函数的话,就创建一个函数
let ctorFunc = types.functionDeclaration(id, method.params, method.body, method.generator, method.async);
body.push(ctorFunc);
} else { // 类上的方法
const key = method.key.name === 'constructor' ? id : method.key;
let left = types.memberExpression(types.memberExpression(id, types.identifier('prototype')), method.key)
let right = types.functionExpression(method.key /* 函数的名字 这里传null就是匿名函数 */, method.params, method.body, method.generator, method.async);
let right = types.functionExpression(key /* 函数的名字 这里传null就是匿名函数 */, method.params, method.body, method.generator, method.async);

let func = types.assignmentExpression('=', left, right)
body.push(func)
Expand Down

0 comments on commit 945c7d9

Please sign in to comment.