Distinguishing a Script and a Module

With ES2015 and later, a JavaScript program can be either a script or a module. It is a very important distinction, a parser such as Esprima needs to know the type of the source to be able to analyze its syntax correctly. This is achieved by choosing parseScript function to parse a script and parseModule function to parse a module.

An example of parsing a script:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parseScript('answer = 42');
  4. Script {
  5. type: 'Program',
  6. body: [ ExpressionStatement { type: 'ExpressionStatement', expression: [Object] } ],
  7. sourceType: 'script' }

An example of parsing a module:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parseModule('import { sqrt } from "math.js"');
  4. Module {
  5. type: 'Program',
  6. body:
  7. [ ImportDeclaration {
  8. type: 'ImportDeclaration',
  9. specifiers: [Object],
  10. source: [Object] } ],
  11. sourceType: 'module' }

Failing to choose the correct parsing function can lead to a mistaken observation that Esprima does not support a certain syntax. Take a look at this example:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parseScript('export const answer = 42');
  4. Error: Line 1: Unexpected token

Instead of producing the syntax tree, the parser throws an exception. This is the correct behavior, an export statement can only be part of a module, not a script. Thus, the parser properly determines that such a source program is invalid.

Note: In the previous versions (Esprima <= 3.1), there was a single parsing function, parse. To distinguish between parsing a script and a module, the sourceType property in the configuration object needs to be specified, either as "script" (also the default value) or "module". While this parse function is still supported in Esprima 4 for API backward compatibility, its usage is highly discouraged and the support for it may be removed in a future version.