How to use esprima

Comprehensive esprima code examples:

How to use esprima.tokenize:

5
6
7
8
9
10
11
12
13
14
15
const rawData = fs.readFileSync('./src/dataset.json');
const dataset = JSON.parse(rawData);


function tokenizeCode(code) {
    try {
        const tokens = esprima.tokenize(code);
        return tokens.map((token) => token.value);
    } catch (error) {
        console.error(error);
        return [];

How to use esprima.Syntax:

44
45
46
47
48
49
50
51
52
53
54
  AwaitExpression,
  WhileStatement,
  ThrowStatement,
  SequenceExpression,
  ContinueStatement
} = esprima.Syntax;


function isGettextCall(callExpression) {
  return callExpression.callee.type === Identifier &&
    callExpression.callee.name === GETTEXT_FUNCTION_NAME;

How to use esprima.ClassExpression:

407
408
409
410
411
412
413
414
415
416
417
418
  append(indent.substring(0, indent.length - 2) + '})()', state);
  return false
}


visitClassExpression.test = function(object, path, state) {
  return object.type === Syntax.ClassExpression;
};


/**
 * @public

How to use esprima.ClassDeclaration:

421
422
423
424
425
426
427
428
429
430
431
432
433
  state.g.indentBy++;
  return false;
}


visitClassDeclaration.test = function(object, path, state) {
  return object.type === Syntax.ClassDeclaration;
};




/**

How to use esprima.parseScript:

221
222
223
224
225
226
227
228
229
230
  tolerant: true
}

logger.log(`[ast] analyzing script path=${path}`)

esprima.parseScript(source, opts, function(node) {
  if (_isSuspiciousCall(host, node, path)) {
    if (results.suspicious_script_hosts.indexOf(host) < 0) {
      results.suspicious_script_hosts.push(host)
    }

How to use esprima.parseModule:

58
59
60
61
62
63
64
65
66
67
68
 */
function getPackageExportNames(packagePath) {
  const packageMeta = getPackageMeta(packagePath);
  const packageModulePath = path.join(packagePath, packageMeta.module);
  const moduleFileSource = fs.readFileSync(packageModulePath, "utf8");
  const { body } = esprima.parseModule(moduleFileSource);


  return body.reduce((result, statement) => {
    if (statement.type === "ExportDefaultDeclaration") {
      return result.concat(["default"]);

How to use esprima.parse:

8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
}


function runPass(source, visitors, options) {
  var ast;
  try {
    ast = esprima.parse(source, { comment: true, loc: true, range: true });
  } catch (e) {
    e.message = 'Parse Error: ' + e.message;
    throw e;
  }