const fs = require('fs');
const path = require('path');
const parser = require('@babel/parser');
const {exec} = require('child_process');
const traverse = require('@babel/traverse').default;
const generator = require('@babel/generator').default;
const t = require('@babel/types');
const delLog = sourceCode => {
const ast = parser.parse(sourceCode, {
sourceType: 'module',
plugins: ['jsx'],
});
traverse(ast, {
CallExpression(path) {
if (
path.node.callee.type === 'MemberExpression' &&
path.node.callee.object.name === 'console' &&
path.node.callee.property.name === 'log'
) {
const parent = path.findParent(
p =>
t.isCatchClause(p) ||
(t.isCallExpression(p) && p.node.callee.property.name === 'catch'),
);
if (!parent) {
path.remove();
}
}
},
});
const optimizedCode = generator(ast);
return delUnusedVar(optimizedCode.code);
};
function removeUnusedImports(code) {
const ast = parser.parse(code, {
sourceType: 'module',
plugins: ['js', 'jsx'],
});
traverse(ast, {
ImportDeclaration(path) {
let specifiers = path.node.specifiers;
if (specifiers.length === 0) {
path.remove();
} else {
let length = specifiers.length;
let count = 0;
let delSpec = new Set();
specifiers.forEach(specifier => {
const localName = specifier.local.name;
let bindings = path.scope.bindings[localName];
if (localName === 'React') {
return;
}
if (!bindings.referenced) {
delSpec.add(localName);
count++;
}
});
if (!delSpec.size) {
return;
}
if (count === length) {
path.remove();
return;
}
path.get('specifiers').forEach(spec => {
if (delSpec.has(spec.node.local.name)) {
spec.remove();
}
});
}
},
});
const {code: modifiedCode} = generator(ast);
return modifiedCode;
}
const delUnusedVar = function (code) {
const ast = parser.parse(code, {
sourceType: 'module',
plugins: ['js', 'jsx'],
});
var visitor = {
VariableDeclarator(path) {
var binding = path.scope.getBinding(path.node.id.name);
if (!binding || binding.constantViolations.length > 0) {
return;
}
if (binding.referencePaths.length == 0) {
path.remove();
}
},
};
traverse(ast, visitor);
const {code: modifiedCode} = generator(ast);
return removeUnusedImports(modifiedCode);
};
const removeCodeByPath = filePath => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const modifiedData = delLog(data);
fs.writeFile(filePath, modifiedData, 'utf8', err => {
if (err) {
console.error('Error writing file:', err);
return;
}
exec('npx eslint --fix ' + filePath, (error, stdout, stderr) => {
if (error) {
console.error(`执行命令出错:${error}`);
return;
}
if (stderr) {
console.error(`命令输出错误:${stderr}`);
return;
}
console.log(`命令执行成功,输出:${stdout}`);
});
});
});
};
function traverseFolder(folder) {
fs.readdir(folder, (err, files) => {
if (err) {
console.error(`Error reading directory ${folder}:`, err);
return;
}
files.forEach(file => {
if (file === 'node_modules') {
return;
}
const fullPath = path.join(folder, file);
fs.stat(fullPath, (err, stats) => {
if (err) {
console.error(`Error getting stats of ${fullPath}:`, err);
return;
}
if (stats.isDirectory()) {
const basename = path.basename(fullPath);
if (['component', 'components'].includes(basename)) {
return;
}
traverseFolder(fullPath);
} else {
if (path.extname(fullPath) === '.js') {
removeCodeByPath(fullPath);
}
}
});
});
});
}
const currentDir = path.dirname(__dirname);
const folderPath = path.join(currentDir, 'pages/test-page/test');
traverseFolder(folderPath);