如何让 acornjs 正确地检查私有 class 字段和方法的样式?

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

我正在做一个项目,我需要对我的代码进行样式检查。我想使用 acorn js,但是在尝试解析私有 class 字段和 class 方法时它失败了。

我试过:

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() {} }');

但是当 运行 时它失败了。这是错误消息:

******** 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

我需要能够使用私有 class 字段和方法,但我不知道如何让 acorn 正确解析它。

问题出在 #a = 2 而不是 #b() {}。 这是因为有两个单独的模块:

所以,添加 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() {} }');