1

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

我试过了:

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

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

4

1 回答 1

1

问题是与#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() {} }');
于 2020-04-10T15:23:44.737 回答