Tree-sitter JavaScript Grammar
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
- gotcha The `tree-sitter-javascript` package *provides* the grammar, but it inherently depends on the core `tree-sitter` Python library to function. Many users forget to install `tree-sitter` alongside this grammar package, leading to `ModuleNotFoundError` for `tree_sitter` or issues when trying to instantiate `Parser` objects. Always install both.
- gotcha The underlying `tree-sitter` core library (which `tree-sitter-javascript` leverages) is a C extension. While pre-built wheels are available for many common platforms, certain environments (e.g., specific Linux distributions, custom Python builds, or older Python versions) may require a C compiler (like GCC or Clang) during installation. Lack of a compiler can cause installation failures.
- breaking While the `language()` function provided by `tree-sitter-javascript` is generally stable, major version changes in the upstream `tree-sitter` Python library can introduce breaking API changes for `Parser`, `Tree`, or `Node` objects. Similarly, significant updates to the underlying JavaScript grammar definition (less frequent for the Python binding) could subtly change the structure of the generated ASTs.
Install
-
pip install tree-sitter-javascript tree-sitter
Imports
- language
from tree_sitter_javascript import language
Quickstart
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')}")