Tree-sitter JavaScript Grammar

0.25.0 · active · verified Thu Apr 09

The `tree-sitter-javascript` package provides the JavaScript grammar for the `tree-sitter` parsing library. It allows Python developers to easily load and use the official Tree-sitter JavaScript grammar to parse JavaScript code into concrete syntax trees (CSTs). The current version is 0.25.0, and it follows the release cadence of the upstream Tree-sitter JavaScript grammar, with updates for syntax changes and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load the JavaScript grammar, create a parser, and parse a simple JavaScript code snippet. It then shows how to access the root node and find a specific node type, such as a function declaration, illustrating basic tree traversal.

import tree_sitter
from tree_sitter_javascript import language

# 1. Get the JavaScript language object
JS_LANGUAGE = language()

# 2. Create a parser and set the language
parser = tree_sitter.Parser()
parser.set_language(JS_LANGUAGE)

# 3. Parse some JavaScript code (must be bytes)
code = b"""
function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("World");
"""
tree = parser.parse(code)

# 4. Access the root node and explore the tree
root_node = tree.root_node

print(f"Root node type: {root_node.type}")
print(f"Root node content (first 50 chars): {root_node.text.decode('utf8')[:50]}...")

# Example: Find the 'function_declaration' node
function_node = None
for child in root_node.children:
    if child.type == 'function_declaration':
        function_node = child
        break

if function_node:
    function_name_node = function_node.child_by_field_name('name')
    if function_name_node:
        print(f"Found function name: {function_name_node.text.decode('utf8')}")

view raw JSON →