项目中 console debug 嵌入代码 如何 优雅删除node
黑魔法 babel 基于 ast,以前简单看过一些 ast相关的知识点,想到一个较为实际的场景例子,console 在开发中经常使用,可是 上线是后可能 会遗漏删除,形成 代码不安全(外面人可能会依靠这个console信息点来反推你的代码)。
开发中须要用到资料网址【官方文档】
https://babeljs.io/docs/en/pl...
https://github.com/jamiebuild...
https://astexplorer.net/
一图胜千言,效果以下git
插件开发相关代码:github
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 脚本babel
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.待转换文件async
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() { } }