Home
avatar

.Wang

前端项目移除console日志(一)

前几天请假调休,后端同事说前端项目打印的日志都要去掉。因为有些项目是 node + jq,没有 vite 那些可以直接使用插件去除。

于是今天下午写了一个脚本文件进行处理。

这个脚本文件的功能是:

  1. 遍历项目目录下的所有文件
  2. 查找文件中是否有 console 相关的代码
  3. 如果有,就将这些代码替换为空字符串
  4. 保存文件
  5. 递归处理子目录

思路大概是这样的。

import {
	readdirSync,
	statSync,
	readFileSync,
	writeFileSync,
	existsSync,
	mkdirSync,
} from "node:fs";
import { join } from "node:path";
// 项目根目录
const ROOT = process.cwd();
// 入口目录
const ENTRY = join(ROOT, "/src/");
// 构建目录
const BUILD_DIR = `${ROOT}/dist`;
// 支持的扩展
const SUPPORTED_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".vue", ".html"];
// 排除的目录
const EXCLUDE_DIRS = [
	"node_modules",
	"dist",
	"build",
	".git",
	".husky",
	".vscode",
	"public",
];

const CONSOLE_REGEX =
	/console\.(log|info|warn|error|debug)\s*\((?:[^()"`]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\((?:[^()"`]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)*\))*\);?/g;

function recursiveDir(dirpath: string) {
	try {
		const files = readdirSync(dirpath);
		files.forEach(file => {
			const filepath = join(dirpath, file);
			const stat = statSync(filepath);
			if (stat.isDirectory() && !EXCLUDE_DIRS.includes(file)) {
				recursiveDir(filepath);
			}

			if (SUPPORTED_EXTENSIONS.some(ext => filepath.endsWith(ext))) {
				onHandlerFile(filepath);
			}
		});
	} catch (error) {
		console.error("遍历目录失败", error);
	}
}

function onHandlerFile(filePath: string) {
	try {
		let content = readFileSync(filePath, "utf-8");
		const originalContent = content;
		content = content.replace(CONSOLE_REGEX, "");
		if (content !== originalContent) {
			if (!existsSync(BUILD_DIR)) mkdirSync(BUILD_DIR, { recursive: true });
			const relativePath = filePath.replace(ENTRY, "");
			const buildPath = join(BUILD_DIR, relativePath);
			writeFileSync(buildPath, content, { encoding: "utf-8" });
		}
	} catch (error) {
		console.error("处理文件失败", error);
	}
}

// 开始执行
console.log("开始移除项目中的console语句...");
const startTime = Date.now();
recursiveDir(ENTRY);
const endTime = Date.now();
console.log(`移除完成! 耗时: ${(endTime - startTime) / 1000}秒`);

然后使用 node 执行这个脚本文件就可以了。

Node 项目总结