我正在使用@typescript-eslint/parser来解析typescript函数,如何获取函数的范围?

问题描述 投票:0回答:1

我正在尝试编写一个读取 TypeScript 文件的脚本,并从中返回函数名称

function getFunctionsFromFile(filePath) {
    const code = readFileSync(filePath, 'utf8');
    const parsed = parse(code, { loc: true }); 
    const functions = [];
    parsed.body.forEach(node => {
        if (node.type === 'FunctionDeclaration') {
            functions.push(node.id.name);
        }
    });
    return functions;
}

它正在读取文件 addNumbers.ts -

export const addNumbers = (num1: number, num2: number) => {
  return num1 + num2
}

并且值

code

'export const addNumbers = (num1: number, num2: number) => {\r\n' +
    '  return num1 + num2\r\n' +
    '}\r\n'

当用

parse
解析它时,我得到了他的错误

const bodyStart = this.block.body?.range[0] ?? -1;
                                                ^
TypeError: Cannot read properties of undefined (reading '0')

注销时

this.block.body
没有范围属性,所以我认为它错误地解析了函数。有没有办法为此定义函数格式?

我尝试使用 typescripts 'createSourceFile' 进行读取,但这并没有像我希望的那样工作,我查看了 @typescript-eslint/parser 的文档,但是我可以传递给

parse
但是找不到可以工作的。

我已将 .eslintrc.js 文件添加到项目中,但这似乎也没有帮助(这是在我尝试读取的 TS 项目的单独文件夹中)

typescript eslint typescript-eslint node.js-fs typescript-eslintparser
1个回答
0
投票

🖐️ typescript-eslint 贡献者在这里。

我在本地尝试过这个,看起来如果你用

range: true
(即
const parsed = parse(code, { range: true });
)解析它就可以工作。我个人对解析器不是很熟悉,但这对我来说似乎只是解析器中的一个错误,是通过对函数参数的引用在代码片段中触发的。考虑在 GitHub 上提交错误报告

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.