How to delete the console debug embedded code gracefully in the project
Black magic babel is based on ast. I have briefly read some ast-related knowledge points before. I thought of a more practical example. The console is commonly used in development, but it may be omitted and deleted after going online, resulting in unsafe code (outsiders may rely on This console information point to reverse your code).
The data URL is needed in development [official document]
https://babeljs.io/docs/en/plugins#plugin-options
https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md
https://astexplorer.net/
A picture is worth a thousand words, and the effect is as follows
Plug-in development related code:
- babel.plugin.rm.conosle.js [plugin code]
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 script
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. Files to be converted
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() {
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。