UNPKG

@fe-fast/code-sweeper

Version:

A lightweight JavaScript/TypeScript code cleaning tool

49 lines (48 loc) 1.77 kB
import { cleanCode } from '@fe-fast/code-sweeper'; export class CodeSweeperWebpackPlugin { constructor(options = {}) { this.options = { ...options, rules: { removeUnusedImports: true, removeUnusedVariables: true, removeConsoleLog: true, removeDebugger: true, formatCode: false, renameToCamelCase: false, ...options.rules, }, }; } apply(compiler) { // 在emit阶段执行代码清理 compiler.hooks.emit.tapAsync('CodeSweeperWebpackPlugin', async (compilation, callback) => { try { // 获取所有源文件路径 const filePaths = Array.from(compilation.fileDependencies) .filter((file) => /\.(js|jsx|ts|tsx)$/.test(file)) .filter((file) => !file.includes('node_modules')); // 对每个文件单独执行代码清理 for (const filePath of filePaths) { try { await cleanCode({ ...this.options, path: filePath, // 确保不会影响构建过程 dryRun: false, skipConfirmation: true }); } catch (fileError) { console.warn(`Code Sweeper warning for ${filePath}:`, fileError); } } callback(); } catch (error) { callback(error); } }); } } export default CodeSweeperWebpackPlugin;