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 specifying the sourceType property in the configuration object. The default value is "script", i.e. the program will be treated as a script and not a module. Another possible value is "module", which instructs the parser to treat the program as a module.

An example of parsing a script:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('answer = 42', { sourceType: 'script' });
  4. Program {
  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.parse('import { sqrt } from "math.js"', { sourceType: 'module' });
  4. Program {
  5. type: 'Program',
  6. body:
  7. [ ImportDeclaration {
  8. type: 'ImportDeclaration',
  9. specifiers: [Object],
  10. source: [Object] } ],
  11. sourceType: 'module' }

Failing to specify the source type 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.parse('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 (treated as a script since sourceType is not specified) is invalid.