javascriptprivateprivate-methodsclass-fieldsacorn

How to get acornjs to properly style check private class fields and methods?


I'm working on a project where I need to use a style check for my code. I want to use acorn js, however it fails when trying to parse private class fields and class methods.

I've tried:

const { Parser } = require('acorn');
const privateMethods = require('acorn-private-methods');
const MyParser = Parser.extend(
  require("acorn-private-methods")
)
MyParser.parse('class X {#a =2; #b() {} }');

However it fails when running. This is the error message:

******** Severe error(s) on main thread (0) ********
SyntaxError: Unexpected token (1:12)
   pos: 12
   loc: {[Position] line: 1, column: 12 }
   raisedAt: 13
  var err = new SyntaxError(message);
            ^
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:2844:13
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:690:8
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:684:26
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:2623:8
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:1389:23
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:1378:8
    at parseClassElement (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn-private-methods/index.js:13:46)
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:1317:26
    at parseClass (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn-private-methods/node_modules/acorn-private-class-elements/index.js:78:29)
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:839:17
    at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:749:23
    at parse (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:552:15)
    at parse (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:575:35)
    at c:/Users/awheeler/Desktop/Imagine/imagine/util/acornStyle.js:61:10
    at c:/Users/awheeler/Desktop/Imagine/imagine/util/style.js:28:20

I need to be able to use private class fields and methods, but I don't know how to get acorn to parse it properly.


Solution

  • The issue is with #a = 2 and not with #b() {}. This is because there are two separate modules for:

    So, add acton-class-fields:

    const { Parser } = require('acorn');
    const privateMethods = require('acorn-private-methods');
    const classFields = require('acorn-class-fields');
    const MyParser = Parser
      .extend(privateMethods)
      .extend(classFields);
    MyParser.parse('class X {#a =2; #b() {} }');