编写脚本来识别前端项目中未使用的依赖包

背景

        随着前端项目中使用的依赖包越来越多,而其中一部分依赖包可能并未被项目所使用,手动查找这些依赖包既耗时又繁琐。未使用的依赖包会增加项目的大小,这可能会导致下载和安装你的应用所需的时间更长。并且在构建项目时,构建工具需要处理所有的依赖包。未使用的依赖包可能会不必要地增加构建时间,特别是在大型项目中。

实现

        编写脚本来识别前端项目中未使用的依赖包:

  1. 读取根目录下的 package.json 文件。
  2. 递归遍历目录获取所有文件路径,并且跳过 excludeDirs 中指定的目录。
  3. 检查依赖是否在文件中被引用,并找到未使用的依赖。
  4. 执行检查并报告结果。
const fs = require("fs")
const path = require("path")

const projectDir = path.resolve(".") // 当前项目目录
const excludeDirs = ["node_modules", ".git", "mock", "idm-fe", "dist"] // 应该排除的目录

// 读取并解析package.json
function readPackageJson() {
  const packageJsonPath = path.join(projectDir, "package.json")
  if (!fs.existsSync(packageJsonPath)) {
    console.error("package.json not found.")
    process.exit(1)
  }
  return JSON.parse(fs.readFileSync(packageJsonPath, "utf8"))
}

// 递归遍历目录获取所有文件路径
function getAllFiles(dirPath, arrayOfFiles) {
  const files = fs.readdirSync(dirPath)
  arrayOfFiles = arrayOfFiles || []

  files.forEach(function (file) {
    if (fs.statSync(dirPath + "/" + file).isDirectory()) {
      if (!excludeDirs.includes(file)) {
        arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles)
      }
    } else {
      arrayOfFiles.push(path.join(dirPath, "/", file))
    }
  })

  return arrayOfFiles
}

// 检查依赖是否在文件中被引用,包括动态引用
function isDependencyUsed(files, dependency) {
  // 这两个正则表达式的目的是为了在文件中找到对指定依赖的引用,无论这些引用是静态的还是动态的。
  // 匹配require('dependency') require(dependency) require(`dependency`) 或 from “dependency”......
  const regexStaticImport = new RegExp(
    `require\\(['"\`]${dependency}['"\`]|from ['"\`]${dependency}['"\`]`,
    "i"
  )
  const regexDynamicImport = new RegExp(
    `import\\(['"\`]${dependency}['"\`]\\)`,
    "i"
  )
  return files.some((file) => {
    const fileContent = fs.readFileSync(file, "utf8")
    return (
      regexStaticImport.test(fileContent) ||
      regexDynamicImport.test(fileContent)
    )
  })
}

function findUnusedDependencies() {
  const {
    dependencies
  } = readPackageJson()
  const allFiles = getAllFiles(projectDir)
  const unusedDependencies = []
  Object.keys(dependencies).forEach((dependency) => {
    if (!isDependencyUsed(allFiles, dependency)) {
      unusedDependencies.push(dependency)
    }
  })

  return unusedDependencies
}

const unusedDependencies = findUnusedDependencies()
if (unusedDependencies.length > 0) {
  console.log("未使用的依赖:", unusedDependencies.join(", "))
} else {
  console.log("所有依赖都已使用。")
}

        我们可以对我们的项目来进行检测,然后删除一些并没有使用过的包,可以增加项目依赖包的安装速度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值