zoukankan      html  css  js  c++  java
  • babel 常用操作

    code to ast

    const { parse } = babel;
    
    const code = `
      for (let k in ${data}) {
         let ${path.__cxt} = _setCxt(k, ${data});
      }
    `;
    const ast = parse(code);
    

    ast to code

    const { default: generate } = require("@babel/generator");
    const { code } = generate(path.node);
    

    在顶层添加静态函数

    function _setCxt(k, data) {
    }
    
    // https://babeljs.io/docs/en/babel-traverse
    traverse(state.file.ast, {
      Program(path) {
        path.unshiftContainer("body", parse(`${_setCxt}`).program.body[0]);
      }
    });
    
    // or
    
    export default function (babel) {
      return {
        visitor: {
          Program: {
            enter(path) {
             path.unshiftContainer("body", parse(`${_setCxt}`).program.body[0]);
            }
          }
        }
      };
    }
    

    获取父节点

    path.parent; // node
    path.parentPath // path
    
    // 返回true则返回查找到的parent,可以返回false来遍历父节点。
    path.findParent(pPath => {
     return true;
    })
    

    path类型判断

    path.type === "Identifier";
    path.isIdentifier();
    

    用另一个替换当前节点

    const { types: t } = babel;
    
    // replaceWith(replacement: Node | NodePath): void;
    path.replaceWith(t.Identifier("a"));
    

    删除path

    path.remove()
    
  • 相关阅读:
    5、文件处理
    6、Python模块
    4、字典使用
    3、列表 list
    1、Python基础
    2、循环判断
    配置LOG4J(log4j-1.2.17)
    File /WEB-INF/web.xml not found...
    关于TOMCAT的 ROOT/WEB-INF/web.xml的配置
    tomcat 配置系列3
  • 原文地址:https://www.cnblogs.com/ajanuw/p/12284116.html
Copyright © 2011-2022 走看看