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:
- $ node
- > var esprima = require('esprima')
- > esprima.parse('answer = 42', { sourceType: 'script' });
- Program {
- type: 'Program',
- body: [ ExpressionStatement { type: 'ExpressionStatement', expression: [Object] } ],
- sourceType: 'script' }
An example of parsing a module:
- $ node
- > var esprima = require('esprima')
- > esprima.parse('import { sqrt } from "math.js"', { sourceType: 'module' });
- Program {
- type: 'Program',
- body:
- [ ImportDeclaration {
- type: 'ImportDeclaration',
- specifiers: [Object],
- source: [Object] } ],
- 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:
- $ node
- > var esprima = require('esprima')
- > esprima.parse('export const answer = 42');
- 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.