How do I use the node-tree-sitter module from typescript?

1.5k Views Asked by At

From looking at pull requests & issues I see there are typescript definitions (possibly currently out of date) in the node-tree-sitter module; how do I access these definitions from typescript, and what would be the equivalent of the following node-tree-sitter sample javascript code in typescript?

const Parser = require('tree-sitter');
const JavaScript = require('tree-sitter-javascript');

const parser = new Parser();
parser.setLanguage(JavaScript);

const sourceCode = 'let x = 1; console.log(x);';
const tree = parser.parse(sourceCode);

console.log(tree.rootNode.toString());
1

There are 1 best solutions below

0
On BEST ANSWER

The tree-sitter module doesn't have a separate @types/tree-sitter module (like some other modules) but instead bundles a tree-sitter.d.ts type definition file with the tree-sitter module itself. You can find this file in your node_modules/tree-sitter directory. TypeScript finds this file automatically when you import tree-sitter. Thus you can rewrite the sample JavaScript code in TypeScript as follows:

import Parser = require('tree-sitter');
import JavaScript = require('tree-sitter-javascript');

const parser: Parser = new Parser();
parser.setLanguage(JavaScript);

const sourceCode: string = 'let x = 1; console.log(x);';
const tree: Parser.Tree = parser.parse(sourceCode);

console.log(tree.rootNode.toString());