UNPKG

10.6 kBMarkdownView Raw
1[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree)
2[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree)
3[![Build Status](https://github.com/eslint/espree/workflows/CI/badge.svg)](https://github.com/eslint/espree/actions)
4[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE)
5
6# Espree
7
8Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima.
9
10## Usage
11
12Install:
13
14```
15npm i espree
16```
17
18To use in an ESM file:
19
20```js
21import * as espree from "espree";
22
23const ast = espree.parse(code);
24```
25
26To use in a Common JS file:
27
28```js
29const espree = require("espree");
30
31const ast = espree.parse(code);
32```
33
34## API
35
36### `parse()`
37
38`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters.
39
40- `code` [string]() - the code which needs to be parsed.
41- `options (Optional)` [Object]() - read more about this [here](#options).
42
43```js
44import * as espree from "espree";
45
46const ast = espree.parse(code);
47```
48
49**Example :**
50
51```js
52const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 });
53console.log(ast);
54```
55
56<details><summary>Output</summary>
57<p>
58
59```
60Node {
61 type: 'Program',
62 start: 0,
63 end: 15,
64 body: [
65 Node {
66 type: 'VariableDeclaration',
67 start: 0,
68 end: 15,
69 declarations: [Array],
70 kind: 'let'
71 }
72 ],
73 sourceType: 'script'
74}
75```
76
77</p>
78</details>
79
80### `tokenize()`
81
82`tokenize` returns the tokens of a given code. It takes two parameters.
83
84- `code` [string]() - the code which needs to be parsed.
85- `options (Optional)` [Object]() - read more about this [here](#options).
86
87Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array
88
89**Example :**
90
91```js
92import * as espree from "espree";
93
94const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 });
95console.log(tokens);
96```
97
98<details><summary>Output</summary>
99<p>
100
101```
102Token { type: 'Keyword', value: 'let', start: 0, end: 3 },
103Token { type: 'Identifier', value: 'foo', start: 4, end: 7 },
104Token { type: 'Punctuator', value: '=', start: 8, end: 9 },
105Token { type: 'String', value: '"bar"', start: 10, end: 15 }
106```
107
108</p>
109</details>
110
111### `version`
112
113Returns the current `espree` version
114
115### `VisitorKeys`
116
117Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys)
118
119### `latestEcmaVersion`
120
121Returns the latest ECMAScript supported by `espree`
122
123### `supportedEcmaVersions`
124
125Returns an array of all supported ECMAScript versions
126
127## Options
128
129```js
130const options = {
131 // attach range information to each node
132 range: false,
133
134 // attach line/column location information to each node
135 loc: false,
136
137 // create a top-level comments array containing all comments
138 comment: false,
139
140 // create a top-level tokens array containing all tokens
141 tokens: false,
142
143 // Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, or 13 to specify the version of ECMAScript syntax you want to use.
144 // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), or 2022 (same as 13) to use the year-based naming.
145 // You can also set "latest" to use the most recently supported version.
146 ecmaVersion: 3,
147
148 allowReserved: true, // only allowed when ecmaVersion is 3
149
150 // specify which type of script you're parsing ("script", "module", or "commonjs")
151 sourceType: "script",
152
153 // specify additional language features
154 ecmaFeatures: {
155
156 // enable JSX parsing
157 jsx: false,
158
159 // enable return in global scope (set to true automatically when sourceType is "commonjs")
160 globalReturn: false,
161
162 // enable implied strict mode (if ecmaVersion >= 5)
163 impliedStrict: false
164 }
165}
166```
167
168## Esprima Compatibility Going Forward
169
170The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same.
171
172Espree may also deviate from Esprima in the interface it exposes.
173
174## Contributing
175
176Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues).
177
178Espree is licensed under a permissive BSD 2-clause license.
179
180## Security Policy
181
182We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md).
183
184## Build Commands
185
186* `npm test` - run all linting and tests
187* `npm run lint` - run all linting
188
189## Differences from Espree 2.x
190
191* The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics.
192* Trailing whitespace no longer is counted as part of a node.
193* `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`.
194* The `esparse` and `esvalidate` binary scripts have been removed.
195* There is no `tolerant` option. We will investigate adding this back in the future.
196
197## Known Incompatibilities
198
199In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change.
200
201### Esprima 1.2.2
202
203* Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs.
204* Espree does not parse `let` and `const` declarations by default.
205* Error messages returned for parsing errors are different.
206* There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn.
207
208### Esprima 2.x
209
210* Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2.
211
212## Frequently Asked Questions
213
214### Why another parser
215
216[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration.
217
218We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API.
219
220With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima.
221
222### Have you tried working with Esprima?
223
224Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support.
225
226### Why don't you just use Acorn?
227
228Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint.
229
230We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better.
231
232### What ECMAScript features do you support?
233
234Espree supports all ECMAScript 2021 features and partially supports ECMAScript 2022 features.
235
236Because ECMAScript 2022 is still under development, we are implementing features as they are finalized. Currently, Espree supports:
237
238* [Class instance fields](https://github.com/tc39/proposal-class-fields)
239* [Class private instance methods and accessors](https://github.com/tc39/proposal-private-methods)
240* [Class static fields, static private methods and accessors](https://github.com/tc39/proposal-static-class-features)
241* [RegExp match indices](https://github.com/tc39/proposal-regexp-match-indices)
242* [Top-level await](https://github.com/tc39/proposal-top-level-await)
243* [Class static initialization blocks](https://github.com/tc39/proposal-class-static-block)
244* [Ergonomic brand checks for Private Fields](https://github.com/tc39/proposal-private-fields-in-in)
245
246See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized.
247
248### How do you determine which experimental features to support?
249
250In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features.