100 lines
2.7 KiB
JavaScript
100 lines
2.7 KiB
JavaScript
/**
|
||
* 清理 Vue 文件中的 console.log 调试语句
|
||
* 保留 console.error 和 console.warn
|
||
*/
|
||
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
// 需要清理的目录
|
||
const targetDirs = [
|
||
'src/views',
|
||
'src/components'
|
||
];
|
||
|
||
// 统计信息
|
||
let totalFiles = 0;
|
||
let cleanedFiles = 0;
|
||
let totalLogsRemoved = 0;
|
||
|
||
/**
|
||
* 递归遍历目录
|
||
*/
|
||
function walkDir(dir, callback) {
|
||
const files = fs.readdirSync(dir);
|
||
|
||
files.forEach(file => {
|
||
const filePath = path.join(dir, file);
|
||
const stat = fs.statSync(filePath);
|
||
|
||
if (stat.isDirectory()) {
|
||
walkDir(filePath, callback);
|
||
} else if (file.endsWith('.vue') || file.endsWith('.js') || file.endsWith('.ts')) {
|
||
callback(filePath);
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 清理文件中的 console.log
|
||
*/
|
||
function cleanFile(filePath) {
|
||
totalFiles++;
|
||
|
||
let content = fs.readFileSync(filePath, 'utf-8');
|
||
const originalContent = content;
|
||
|
||
// 计算原有的 console.log 数量
|
||
const logCount = (content.match(/console\.log\(/g) || []).length;
|
||
|
||
if (logCount === 0) {
|
||
return;
|
||
}
|
||
|
||
// 移除 console.log 语句(保留 console.error 和 console.warn)
|
||
// 匹配整行的 console.log
|
||
content = content.replace(/^[ \t]*console\.log\([^)]*\);?\s*$/gm, '');
|
||
|
||
// 移除行内的 console.log(可能在其他代码之后)
|
||
content = content.replace(/console\.log\([^)]*\);?\s*/g, '');
|
||
|
||
// 清理多余的空行(但保留最多2个连续空行)
|
||
content = content.replace(/\n\n\n+/g, '\n\n');
|
||
|
||
// 如果内容有变化,写回文件
|
||
if (content !== originalContent) {
|
||
fs.writeFileSync(filePath, content, 'utf-8');
|
||
cleanedFiles++;
|
||
totalLogsRemoved += logCount;
|
||
console.log(`✓ 清理 ${path.relative(process.cwd(), filePath)} (移除 ${logCount} 个 console.log)`);
|
||
}
|
||
}
|
||
|
||
// 主函数
|
||
console.log('='.repeat(60));
|
||
console.log('开始清理前端 console.log 调试语句');
|
||
console.log('='.repeat(60));
|
||
console.log();
|
||
|
||
targetDirs.forEach(dir => {
|
||
const fullPath = path.join(__dirname, dir);
|
||
if (fs.existsSync(fullPath)) {
|
||
console.log(`正在扫描目录: ${dir}`);
|
||
walkDir(fullPath, cleanFile);
|
||
} else {
|
||
console.log(`⚠ 目录不存在: ${dir}`);
|
||
}
|
||
});
|
||
|
||
console.log();
|
||
console.log('='.repeat(60));
|
||
console.log('清理完成!');
|
||
console.log('='.repeat(60));
|
||
console.log(`总文件数: ${totalFiles}`);
|
||
console.log(`清理文件数: ${cleanedFiles}`);
|
||
console.log(`移除的 console.log 总数: ${totalLogsRemoved}`);
|
||
console.log();
|
||
console.log('注意:console.error 和 console.warn 已保留');
|
||
console.log('='.repeat(60));
|
||
|