purify-code
Version:
A CLI tool to remove console.log, debugger, and comments from JS/TS files
29 lines (25 loc) • 950 B
JavaScript
import fs from "fs";
import path from "path";
export function cleanFolder(dir) {
fs.readdirSync(dir).forEach((file) => {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
cleanFolder(fullPath);
} else if (/\.(js|ts)$/.test(file)) {
const code = fs.readFileSync(fullPath, "utf-8");
const cleaned = cleanCode(code);
fs.writeFileSync(fullPath, cleaned);
console.log(`✔ Cleaned: ${fullPath}`);
}
});
}
function cleanCode(code) {
return code
.replace(/console\.log\(.*?\);?/g, "") // Remove console.logs
.replace(/debugger;?/g, "") // Remove debuggers
.replace(/\/\/.*?(TODO|FIXME).*?$/gm, "") // Remove TODO/FIXME comments
.replace(/\/\/.*$/gm, "") // Remove single-line comments
.replace(/\/\*[\s\S]*?\*\//gm, "") // Remove block comments
.replace(/^\s*\n/gm, ""); // Remove empty lines
}