babel: 从0开始实现一个babel插件

官方文档
参考: 链接
在线js代码转换ast

– eg 移除代码中共console,debugger及自定义DEBUG的关键词

// mybabel.config.js

// t就是babel-types,可以更方便的让我们匹配if for之类的关键词
module.exports = ({ types: t }) => {
  const isIF = (node) => t.isIfStatement(node);
  const isDEBUGG = (name) => name === "DEBUG";
  const isCONSOLE = (name) => name === "console";
  return {
    visitor: {
      // visitor是ast的访问者
      IfStatement(path, { opts }) {
        const { test } = path.node;
        if (isIF(path.node) && isDEBUGG(test.name)) {
          opts.removeDebug && path.remove();
        }
      },
      Identifier(path) {
        if (isIF(path.parent) && isDEBUGG(path.node.name)) {
          path.replaceWith(t.booleanLiteral(true));
        }
      },
      ExpressionStatement(path, { opts }) {
        if (!(path.node.expression && path.node.expression.callee)) return;
        const { object, property } = path.node.expression.callee;
        if (!isCONSOLE(object.name)) return;
        // 根据参数保留某些console方法
        if ((opts.exclude || []).includes(property.name)) return;
        path.remove();
      },
      DebuggerStatement(path, { opts }) {
        opts.noDebugger && path.remove();
      },
    },
  };
};

/package.json
{
  "name": "babel",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "babel": "babel ./src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "babel": {
    "plugins": [
      [
        "./mybabel.config.js",
        {
          "noDebugger": true,
          "removeDebug": true,
          "exclude": [
            "info"
          ]
        }
      ]
    ]
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3"
  }
}


要处理的文件

/src/index.js
const a = 1;
console.log(a);
var b = 3
debugger;
if (DEBUG) {
  console.log(2222)
}
console.log(7);
console.info(8);

分析: 将/src/test.js代码放到在线js代码转换ast可以看出

  1. debugger对应的AST里面的key为DebuggerStatement,在vistor也可以看到DebuggerStatement,然后就可以在DebuggerStatement内处理自己的逻辑
    DebuggerStatement提供两个参数 path,state
    path(当前匹配节点上下文) state (获取babel插件配置的参数)
    查询文档path提供replaceWith,remove方法然后就可以匹配关键词进行删除了
npm run babel
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值