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