why esprima works fine in online browser demo, but failed locally

500 views Asked by At

When I try to parse a snippet of code with the following script, it failed (using [email protected]). However it works fine in the esprima online browser demo, shown in the screenshot below.

var esprima = require('esprima');
var fs = require('fs');

const raw_string = String.raw`export { AppCache , addOrReplaceCacheableGroup , findCacheableGroup , CacheTimeoutData } from 's' ; export { AppCacheAction , AppCacheActionType , CacheGroupAction , AddToCacheAction } from 's' ; export { cacheGroup , addToCache } from 's' ; export { appCacheReducer } from 's' ;`;

ast_string = JSON.stringify(esprima.parseScript(raw_string, { range: true }), null, 2);
fs.writeFile('./ast_data/test.json', ast_string, () => {});

enter image description here

The output error message is as follows:

/usr/lib/nodejs/esprima/dist/error-handler.js:17
            throw error;
            ^
Error: Line 1: Unexpected token
    at ErrorHandler.constructError (/usr/lib/nodejs/esprima/dist/error-handler.js:21:21)
    at ErrorHandler.createError (/usr/lib/nodejs/esprima/dist/error-handler.js:37:26)
    at Parser.unexpectedTokenError (/usr/lib/nodejs/esprima/dist/parser.js:162:38)
    at Parser.tolerateUnexpectedToken (/usr/lib/nodejs/esprima/dist/parser.js:175:41)
    at Parser.parseStatementListItem (/usr/lib/nodejs/esprima/dist/parser.js:1542:30)
    at Parser.parseScript (/usr/lib/nodejs/esprima/dist/parser.js:2900:28)
    at parse (/usr/lib/nodejs/esprima/dist/esprima.js:63:60)
    at Object.parseScript (/usr/lib/nodejs/esprima/dist/esprima.js:86:12)
    at Object.<anonymous> (/home/bob/Desktop/js_ast/esprima-ast-visitor-1.0.0/ast_gen.js:6:37)
    at Module._compile (internal/modules/cjs/loader.js:778:30)

1

There are 1 answers

0
Bob Li On

I solved my problem by changing esprima.parseScript to esprima.parseModule