Search code examples
angularantlr

Antlr4ts not working with Angular Version 13


I am trying to use antlr4ts with angular version 13 when I am trying to parse any string I am getting error. The below is my service code where I am trying to parse a string

import { Injectable } from '@angular/core';
import { ANTLRInputStream, CommonToken, CommonTokenStream } from 'antlr4ts';
import { MYLexer } from 'src/assets/lexpar/MyLexer';
import {
  DatuMapParser,
  ProgramContext,
} from 'src/assets/lexpar/MyParser';

declare var process: any;

@Injectable({
  providedIn: 'root',
})
export class TransformationService {
  inputStream: ANTLRInputStream;
  lexer: DatuMapLexer;
  parser: DatuMapParser;
  tokenStream: CommonTokenStream;
  ruleTree: ProgramContext;

  constructor() {}

  parseRule(ruleText: string): any {
    this.inputStream = new ANTLRInputStream(ruleText);
    this.lexer = new MyLexer(this.inputStream);
    this.tokenStream = new CommonTokenStream(this.lexer);
    this.parser = new MyParser(this.tokenStream);
    this.ruleTree = this.parser.program();
    return this.ruleTree;
  }
}

I am getting below error in browser console

ERROR Error: Uncaught (in promise): ReferenceError: process is not defined ReferenceError: process is not defined at 74 (util.js:109:1) at __webpack_require__ (bootstrap:19:1) at 6094 (assertion_error.js:35:16) at __webpack_require__ (bootstrap:19:1) at 431 (assert.js:36:22) at __webpack_require__ (bootstrap:19:1) at 8043 (ANTLRInputStream.js:15:16) at __webpack_require__ (bootstrap:19:1) at 3039 (index.js:20:14) at __webpack_require__ (bootstrap:19:1) at resolvePromise (zone.js:1211:1) at resolvePromise (zone.js:1165:1) at zone.js:1278:1 at _ZoneDelegate.invokeTask (zone.js:406:1) at Object.onInvokeTask (core.mjs:25444:1) at _ZoneDelegate.invokeTask (zone.js:405:1) at Zone.runTask (zone.js:178:1) at drainMicroTaskQueue (zone.js:585:1)

could anyone please help me with fixing this issue


Solution

  • This error is a typical one when you try to use a library that contains access to Node.js modules in a browser. Since you cannot use Node.js there, you obviously cannot use any API that makes use of Node.js functionality. The other parts of the library, however, are usable also in a Browser. Unfortunately, there's still the import of the Node.js packages in the code and you have to take care to provide them somehow.

    The usually approach with bundlers like Webpack or rollup.js is to shim those (using polyfills). IIRC Webpack does this automatically, so I wonder why you see the error. In rollup.js you have to explicitly import polyfills (e.g. npm --save-dev i rollup-plugin-polyfill-node) and configure the packer with them.

    They will then insert the shims in the place of the imports and the error should go away.