Using Esprima with Rhino or Nashorn

With Rhino or Nashorn, Esprima must be loaded from its source using the load function, such as:

  1. load('/path/to/esprima.js');

The module esprima will be available as part of the global object.

The following session with Nashorn shell, jrunscript, demonstrates the usage:

  1. $ jrunscript
  2. nashorn> load('esprima.js')
  3. nashorn> ast = esprima.parseScript('const answer = 42')
  4. [object Object]
  5. nashorn> print(JSON.stringify(ast, null, 2))
  6. {
  7. "type": "Program",
  8. "body": [
  9. {
  10. "type": "VariableDeclaration",
  11. "declarations": [
  12. {
  13. "type": "VariableDeclarator",
  14. "id": {
  15. "type": "Identifier",
  16. "name": "answer"
  17. },
  18. "init": {
  19. "type": "Literal",
  20. "value": 42,
  21. "raw": "42"
  22. }
  23. }
  24. ],
  25. "kind": "const"
  26. }
  27. ],
  28. "sourceType": "script"
  29. }