You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python脚本解析TypeScript文件并提取方法代码?

如何用Python提取TypeScript文件中的函数及其代码

手动遍历行检测关键字的方式确实容易出错,比如函数内部嵌套函数、多行函数声明、箭头函数等场景都无法正确处理。你遇到的typescript PyPI包已被弃用,所以导入失败是正常的,下面给两种可靠的替代方案:

方案一:使用tree-sitter解析TypeScript AST

tree-sitter是一个高效的语法解析库,支持TypeScript,能直接生成抽象语法树(AST),精准定位函数节点。

步骤

  1. 安装依赖
    pip install tree-sitter
    git clone https://github.com/tree-sitter/tree-sitter-typescript.git
    
  2. 编写Python脚本
    import tree_sitter
    from tree_sitter import Language, Parser
    
    # 加载TypeScript语言定义
    Language.build_library(
        'build/my-languages.so',
        ['tree-sitter-typescript/typescript']
    )
    TS_LANGUAGE = Language('build/my-languages.so', 'typescript')
    parser = Parser()
    parser.set_language(TS_LANGUAGE)
    
    def extract_ts_functions(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            code = f.read()
        tree = parser.parse(bytes(code, 'utf-8'))
        root_node = tree.root_node
    
        functions = []
    
        # 递归遍历AST节点
        def traverse(node):
            # 匹配普通函数声明
            if node.type == 'function_declaration':
                name_node = node.child_by_field_name('name')
                if name_node:
                    func_name = name_node.text.decode('utf-8')
                    # 获取函数的完整代码范围
                    start_byte = node.start_byte
                    end_byte = node.end_byte
                    func_code = code[start_byte:end_byte]
                    functions.append((func_name, func_code))
            # 匹配导出的函数声明
            elif node.type == 'export_named_declaration':
                declaration = node.child_by_field_name('declaration')
                if declaration and declaration.type == 'function_declaration':
                    name_node = declaration.child_by_field_name('name')
                    if name_node:
                        func_name = name_node.text.decode('utf-8')
                        start_byte = declaration.start_byte
                        end_byte = declaration.end_byte
                        func_code = code[start_byte:end_byte]
                        functions.append((f'export {func_name}', func_code))
            # 递归遍历子节点
            for child in node.children:
                traverse(child)
    
        traverse(root_node)
        return functions
    
    # 使用示例
    if __name__ == '__main__':
        target_file = 'your-file.ts'
        funcs = extract_ts_functions(target_file)
        for name, code in funcs:
            print(f'\n=== 函数: {name} ===')
            print(code)
    

方案二:调用Node.js的TypeScript官方API

TypeScript官方提供了编译器API,能完美处理所有TS语法特性。可以用Python调用Node.js脚本实现提取逻辑,兼容性最佳。

步骤

  1. 确保已安装Node.js和TypeScript
    npm install -g typescript
    
  2. 编写Node.js脚本(命名为extract-funcs.js)
    const ts = require('typescript');
    const fs = require('fs');
    
    function extractFunctions(filePath) {
        const sourceCode = fs.readFileSync(filePath, 'utf-8');
        const sourceFile = ts.createSourceFile(
            filePath,
            sourceCode,
            ts.ScriptTarget.Latest,
            true
        );
    
        const functions = [];
    
        ts.forEachChild(sourceFile, (node) => {
            // 处理普通函数
            if (ts.isFunctionDeclaration(node) && node.name) {
                const funcCode = sourceCode.substring(node.getStart(), node.getEnd());
                functions.push({
                    name: node.name.getText(),
                    code: funcCode
                });
            }
            // 处理导出的函数
            else if (ts.isExportNamedDeclaration(node)) {
                const declaration = node.declaration;
                if (ts.isFunctionDeclaration(declaration) && declaration.name) {
                    const funcCode = sourceCode.substring(declaration.getStart(), declaration.getEnd());
                    functions.push({
                        name: `export ${declaration.name.getText()}`,
                        code: funcCode
                    });
                }
            }
        });
    
        console.log(JSON.stringify(functions));
    }
    
    const targetFile = process.argv[2];
    extractFunctions(targetFile);
    
  3. 编写Python脚本调用该JS文件
    import subprocess
    import json
    
    def extract_ts_functions(file_path):
        result = subprocess.run(
            ['node', 'extract-funcs.js', file_path],
            capture_output=True,
            encoding='utf-8'
        )
        if result.returncode != 0:
            raise Exception(f'提取失败: {result.stderr}')
        return json.loads(result.stdout)
    
    # 使用示例
    if __name__ == '__main__':
        target_file = 'your-file.ts'
        funcs = extract_ts_functions(target_file)
        for func in funcs:
            print(f'\n=== 函数: {func["name"]} ===')
            print(func["code"])
    

方案对比

  • tree-sitter方案:纯Python环境即可运行,解析速度快,适合简单TS场景。
  • Node.js方案:基于官方TS编译器,支持所有TS语法(如装饰器、泛型、箭头函数等),兼容性和准确性最高。

内容的提问来源于stack exchange,提问作者stymoloch37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:34:58