Build up DOM from AST or AST from DOM. Just because DOM is something more familiar to web-developers than AST, though there are tools like esquery or ast-types. ESDOM is forward-compatible with esquery, so everything is done via esdom can be painlessly refactored to use esquery.
Works both in browsers and node.
$ npm install esdom
var esdom = ;var esprima = ;var escodegen = ;var ast = esprima;var el = esdom;el;ast = esdom;escodegen;
Mapping is done to be compatible with ESQuery selectors as much as possible.
Let’s take an examplary source:
var a = 1;
AST for the source will be:
And resulting HTML:
So all esquery css selectors work just fine with that html, with some exceptions:
:last-childselectors always return non-empty result, where esquery may return nothing. For example, selector
VariableDeclarator > Identifier:first-childreturns
<Identifier>, where esquery returns
- Nested attribute selector should be replaced with subject indicator (or :has):
![attr] > [subAttr=xyz]
- To select custom esquery pseudos like
:statement, it is recommended to use
esdom/query, otherwise it should be replaced with natural DOM class
- Regular expression and conditional selectors should be replaced with according css selectors.
In all other regards it works just the same.
- esquery is inable to select list of nodes, like all function params, or all function body statements. With esdom you can do
.Function > [prop="params"].
- esdom might be somewhat slow in browsers due to using browser API. In node, DOM is emulated via dom-lite, so it’s times faster.
- esdom work only with ES5.
ESDOM also provides helpful scope/variable analysis, marking nodes with additional
data- attributes. To analyze DOM, call
esdom.analyze(dom), and it will set attributes:
||Global scope flag|
||Parent scope id|
||Variable indicator with unique id|
||Variable declaration flag|
||Variable holding scope|
||Convert AST to DOM element.|
||Build AST from DOM element.|
||Mark up AST nodes|