|
8 | 8 | content: vuepress,最新技术文档,vuepress语法,markdown语法
|
9 | 9 | ---
|
10 | 10 |
|
11 |
| -# redis 增删改查 |
| 11 | +# 检查前端项目和node项目中未被使用的依赖包 |
| 12 | + |
| 13 | +```js |
| 14 | +import fs from 'fs' |
| 15 | +import path from 'path' |
| 16 | +const projectDir = path.resolve("."); // 当前项目目录 |
| 17 | +const excludeDirs = ["node_modules", ".git"]; // 应该排除的目录 |
| 18 | + |
| 19 | +// 读取并解析package.json |
| 20 | +function readPackageJson() { |
| 21 | + const packageJsonPath = path.join(projectDir, "package.json"); |
| 22 | + if (!fs.existsSync(packageJsonPath)) { |
| 23 | + console.error("package.json not found."); |
| 24 | + process.exit(1); |
| 25 | + } |
| 26 | + return JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); |
| 27 | +} |
| 28 | + |
| 29 | +// 递归遍历目录获取所有文件路径 |
| 30 | +function getAllFiles(dirPath, arrayOfFiles) { |
| 31 | + const files = fs.readdirSync(dirPath); |
| 32 | + |
| 33 | + arrayOfFiles = arrayOfFiles || []; |
| 34 | + |
| 35 | + files.forEach(function (file) { |
| 36 | + if (fs.statSync(dirPath + "/" + file).isDirectory()) { |
| 37 | + if (!excludeDirs.includes(file)) { |
| 38 | + arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles); |
| 39 | + } |
| 40 | + } else { |
| 41 | + arrayOfFiles.push(path.join(dirPath, "/", file)); |
| 42 | + } |
| 43 | + }); |
| 44 | + |
| 45 | + return arrayOfFiles; |
| 46 | +} |
| 47 | + |
| 48 | +// 检查依赖是否在文件中被引用,包括动态引用 |
| 49 | +function isDependencyUsed(files, dependency) { |
| 50 | + const regexStaticImport = new RegExp( |
| 51 | + `require\\(['"\`]${dependency}['"\`]|from ['"\`]${dependency}['"\`]`, |
| 52 | + "i" |
| 53 | + ); |
| 54 | + const regexDynamicImport = new RegExp( |
| 55 | + `import\\(['"\`]${dependency}['"\`]\\)`, |
| 56 | + "i" |
| 57 | + ); |
| 58 | + return files.some((file) => { |
| 59 | + const fileContent = fs.readFileSync(file, "utf8"); |
| 60 | + return ( |
| 61 | + regexStaticImport.test(fileContent) || |
| 62 | + regexDynamicImport.test(fileContent) |
| 63 | + ); |
| 64 | + }); |
| 65 | +} |
| 66 | + |
| 67 | +function findUnusedDependencies() { |
| 68 | + const { dependencies } = readPackageJson(); |
| 69 | + const allFiles = getAllFiles(projectDir); |
| 70 | + const unusedDependencies = []; |
| 71 | + |
| 72 | + Object.keys(dependencies).forEach((dependency) => { |
| 73 | + if (!isDependencyUsed(allFiles, dependency)) { |
| 74 | + unusedDependencies.push(dependency); |
| 75 | + } |
| 76 | + }); |
| 77 | + |
| 78 | + return unusedDependencies; |
| 79 | +} |
| 80 | + |
| 81 | +const unusedDependencies = findUnusedDependencies(); |
| 82 | +if (unusedDependencies.length > 0) { |
| 83 | + console.log("未使用的依赖:", unusedDependencies.join(", ")); |
| 84 | +} else { |
| 85 | + console.log("所有依赖都已使用。"); |
| 86 | +} |
| 87 | +``` |
0 commit comments