官方文档
参考: 链接
在线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可以看出
- debugger对应的AST里面的key为DebuggerStatement,在vistor也可以看到DebuggerStatement,然后就可以在DebuggerStatement内处理自己的逻辑
DebuggerStatement提供两个参数 path,state
path(当前匹配节点上下文) state (获取babel插件配置的参数)
查询文档path提供replaceWith,remove方法然后就可以匹配关键词进行删除了
npm run babel