【问题标题】:Is there a way to find only unused JSDoc type definitions?有没有办法只找到未使用的 JSDoc 类型定义?
【发布时间】:2022-01-21 19:04:38
【问题描述】:

例如:

/**
 * A number, or a string containing a number.
 * @typedef {(number|string)} NumberLike
 *
 * Dummy type
 * @typedef {(string|null)} StringLike
 */

/**
 * Set the magic number.
 * @param {NumberLike} x - The magic number.
 */
function setMagicNumber(x) {
}

如您所见,使用了NumberLike,但未使用StringLike 类型,我想在我们的项目中找到所有这些未使用的类型定义。这是一个安装了typescript 的Nodejs 项目。

这是我们的tsconfig.json 文件:

{
  "compilerOptions": {
    "baseUrl": ".",
    "jsx": "react",
    "allowJs": true,
    "checkJs": true,
    "target": "ESNext",
    "noEmit": true,
    "moduleResolution": "node",
    "isolatedModules": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "strictNullChecks": true,
  },
}

【问题讨论】:

  • 当你说“找到”时,你是什么意思具体/字面意思(详细)?
  • @jsejcksn,仅查看未使用类型的列表对我来说就足够了(所以我可以删除它们)

标签: javascript typescript jsdoc


【解决方案1】:

我目前不熟悉 AST 工具(我认为这将是查找此信息的工具领域)。然而,这里有一个例子来说明一个想法:

假设您帖子中的示例 JavaScript 文件保存在 ./module.mjs。这是另一个模块,./find-typedefs.mjs

import {promises as fs} from 'fs';

function getTypedefNames (sourceText) {
  const regex = /@typedef\s+{[^}]+}\s+[A-Za-z]+/g;
  return [...new Set((sourceText.match(regex) ?? [])
    .map(str => str.split(/\s+/).slice(-1)[0]))];
}

async function main () {
  const [filePath] = process.argv.slice(2)
  const text = await fs.readFile(filePath, {encoding: 'utf8'});
  const names = getTypedefNames(text);
  console.log(names.join('\n'));
}

main();

运行文件输出如下:

$ node find-typedefs.mjs module.mjs
NumberLike
StringLike

通过使用函数getTypedefNames 作为可能更多抽象的基础,您可以自动搜索项目中的文件以生成名称列表,然后您可以在每个文件中搜索(例如,计数)。如果您使用的是 VS Code 之类的编辑器,您还可以直接在编辑器的 Find 菜单中使用正则表达式(例如该函数中的表达式)。

希望这会为您节省一些人工眼睛扫描的工作。

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2016-08-10
    • 2014-08-01
    • 2021-12-27
    • 2018-09-16
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多