我的项目中 console debug 嵌入代码 如何 优雅删除
黑魔法 babel 基于 ast,之前简略看过一些 ast相干的知识点,想到一个较为理论的场景例子,console 在开发中罕用,然而 上线是后可能 会脱漏删除,造成 代码不平安(里面人可能会依附这个console信息点来反推你的代码)。
开发中须要用到材料网址【官网文档】
https://babeljs.io/docs/en/pl…
https://github.com/jamiebuild…
https://astexplorer.net/
一图胜千言,成果如下
插件开发相干代码:
-
babel.plugin.rm.conosle.js【插件代码】
module.exports = function (t, option = {}) { const { comment = "noclear" } = option; console.log(option) return { visitor: { MemberExpression(path) { const { node, type, parentPath } = path; const ppPath = parentPath.parentPath; const { node: { leadingComments = [] }, } = ppPath; if (type === "MemberExpression") { const { object } = node; // 存在 行内 正文noclear 会排除删除 if ( object.name === "console" && !leadingComments.some((d) => d.value.includes(comment)) ) { parentPath.remove(); } } }, }, }; };
2.babelScript 脚本
const babel = require("@babel/core");
const fs = require("fs");
const path = require("path");
const fsReadFileWarp = (path) => {
return new Promise((r, j) => {
fs.readFile(
path,
{
encoding: "utf-8",
},
(err, data) => {
if (err) {
j(err);
} else {
r(data);
}
}
);
});
};
const init = async () => {
const oldCode = await fsReadFileWarp(path.join(__dirname,"./test/c.js"));
let result = babel.transformSync(oldCode, {
plugins: [["./babel.plugin.rm.conosle.js", { name: "fangtangxiansheng" }]],
});
console.log(oldCode)
console.log('__ ******输入代码******** __\n')
console.log(result.code)
};
init()
3.待转换文件
console.log('ccc')
function add () {
var a = 123;
console.log('zzz') // noclear
console.log('jjj')
}
function jvb() {
var b = 378;
for(let idx = 0; idx < 10; idx ++) {
b ++
console.log(b)
}
console.log('ccc')
}
class Test {
constructor() {
}
}
发表回复