What is @lezer/javascript?
@lezer/javascript is a parser for JavaScript written using the Lezer parser system. It provides a way to parse JavaScript code into a syntax tree, which can be used for various purposes such as syntax highlighting, code analysis, and transformation.
What are @lezer/javascript's main functionalities?
Parsing JavaScript Code
This feature allows you to parse JavaScript code into a syntax tree. The code sample demonstrates how to parse a simple JavaScript statement and print the resulting syntax tree.
const {parser} = require('@lezer/javascript');
const input = 'const x = 10;';
const tree = parser.parse(input);
console.log(tree.toString());
Syntax Tree Traversal
This feature allows you to traverse the syntax tree. The code sample shows how to use a TreeCursor to iterate over the nodes in the syntax tree and print their types.
const {parser} = require('@lezer/javascript');
const {TreeCursor} = require('@lezer/common');
const input = 'const x = 10;';
const tree = parser.parse(input);
let cursor = tree.cursor();
do {
console.log(cursor.node.type.name);
} while (cursor.next());
Custom Syntax Highlighting
This feature allows you to apply custom syntax highlighting to JavaScript code. The code sample demonstrates how to define a highlighting style and apply it to a parsed syntax tree.
const {parser} = require('@lezer/javascript');
const {highlightTree} = require('@lezer/highlight');
const {styleTags, tags} = require('@lezer/highlight');
const input = 'const x = 10;';
const tree = parser.parse(input);
const highlightStyle = styleTags({
'VariableName': tags.variableName,
'Keyword': tags.keyword,
'Number': tags.number
});
let highlighted = '';
highlightTree(tree, highlightStyle, (from, to, classes) => {
highlighted += input.slice(from, to) + ' [' + classes + '] ';
});
console.log(highlighted);
Other packages similar to @lezer/javascript
acorn
Acorn is a small, fast, JavaScript-based JavaScript parser. It is designed to be modular and can be extended with plugins. Compared to @lezer/javascript, Acorn is more widely used and has a larger community, but it may not integrate as seamlessly with the Lezer ecosystem.
esprima
Esprima is a high-performance, standard-compliant ECMAScript parser written in JavaScript. It is known for its speed and accuracy. While Esprima is similar to @lezer/javascript in terms of functionality, it is more mature and has been used in many production environments.
@lezer/javascript
This is a JavaScript grammar for the
lezer parser system.
It parses ES2020, and supports a "ts"
dialect to parse
TypeScript, and a "jsx"
dialect to parse JSX.
The code is licensed under an MIT license.
0.15.1 (2021-11-12)
Bug fixes
Add support for TypeScript import {type X} from y
syntax.
Indexed TypeScript types can now take type parameters.
Add support for private field syntax.
Rename PropertyNameDefinition node to PropertyDefinition for consistency with other names.
New features
Recognize TypeScript 4.3's override
keyword.