码迷,mamicode.com
首页 > 其他好文 > 详细

[AST Babel] Create a simple babel plugin

时间:2020-02-19 21:14:01      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:The   not   efault   back   pat   const   def   code   exp   

For example, we have the source code:

getVersison(‘3.4.5‘)

function getVersion(versionString) {
    const versionRegex = /(\d)\.(\d)\.(\d+)/
    const [, major, minor, patch] = versionRegex.exec(versionString)
    return {major, minor, patch}
}

 

We want to transform it into:

const _versionRegex = /(\d)\.(\d)\.(\d+)/;
getVersison(‘3.4.5‘)

function getVersion(versionString) {
    const [, major, minor, patch] = _versionRegex.exec(versionString)
    return {major, minor, patch}
}

 

Babel plugin:

export default function (babel) {
  const { types: t } = babel;
  
  return {
    name: "ast-transform", // not required
    visitor: {
      RegExpLiteral(path) {
        const name = path.parent.id.name; //versionRege
        const newIdentifier = path.scope.generateUidIdentifier(name) // _versionRegex
        const variableDeclaration = t.variableDeclaration(‘const‘, [
            t.variableDeclarator(newIdentifier, path.node)
        ]) // const _versionRegex = /(\d)\.(\d)\.(\d+)/;
        
        console.log(variableDeclaration)
        
        
        /*
        - const [, major, minor, patch] = versionRegex.exec(versionString)
        + const [, major, minor, patch] = _versionRegex.exec(versionString)
        */
        path.scope.rename(name, newIdentifier.name)
        
        const program = path.findParent(
         t.isProgram
        )
        
        console.log(program.node.body)
        
        program.node.body.unshift(variableDeclaration) // + const _versionRegex = /(\d)\.(\d)\.(\d+)/;
        
        path.parentPath.remove() // - const versionRegex = /(\d)\.(\d)\.(\d+)/
      }
    }
  };
}

 

[AST Babel] Create a simple babel plugin

标签:The   not   efault   back   pat   const   def   code   exp   

原文地址:https://www.cnblogs.com/Answer1215/p/12332952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!