zoukankan      html  css  js  c++  java
  • [AST Babel] Create a simple babel plugin

    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+)/
          }
        }
      };
    }
  • 相关阅读:
    Exp5
    Exp4
    Exp3
    Exp02
    【TPM】tpm搭建基础指南
    20155316 Exp1 PC平台逆向破解(5)M
    个人早期写的一些组件
    关于spring @scope("prorotype") 和 @aspectj 一起用的问题
    ThreadLocal内存泄漏需要注意的
    Spring IoC 容器大概流程
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12332952.html
Copyright © 2011-2022 走看看