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()
    
  • 相关阅读:
    unit 21
    unit 20
    unit 19
    第十八单元
    17 unit
    ES 中文分词
    ES 的CRUD 简单操作(小试牛刀)
    ES 必备插件的安装
    ES的安装运行
    JAVA_HOME 的设置
  • 原文地址:https://www.cnblogs.com/ajanuw/p/12284116.html
Copyright © 2011-2022 走看看