Using Esprima in a web browser

To use Esprima in a browser environment, it needs to be loaded using the script element. For instance, to load Esprima from a CDN such as unpkg, the HTML document needs to have the following line:

  1. <script src="https://unpkg.com/[email protected]~3.1/dist/esprima.js"></script>

When Esprima is loaded this way, it will be available as a global object named esprima.

Since Esprima supports AMD (Asynchronous Module Definition), it can be loaded with a module loader such as RequireJS:

  1. require(['esprima'], function (parser) {
  2. // Do something with parser, e.g.
  3. var syntax = parser.parse('var answer = 42');
  4. console.log(JSON.stringify(syntax, null, 4));
  5. });