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:
JavaScript
x
7
1
const { Parser } = require('acorn');
2
const privateMethods = require('acorn-private-methods');
3
const MyParser = Parser.extend(
4
require("acorn-private-methods")
5
)
6
MyParser.parse('class X {#a =2; #b() {} }');
7
However it fails when running. This is the error message:
JavaScript
1
23
23
1
******** Severe error(s) on main thread (0) ********
2
SyntaxError: Unexpected token (1:12)
3
pos: 12
4
loc: {[Position] line: 1, column: 12 }
5
raisedAt: 13
6
var err = new SyntaxError(message);
7
^
8
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:2844:13
9
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:690:8
10
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:684:26
11
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:2623:8
12
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:1389:23
13
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:1378:8
14
at parseClassElement (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn-private-methods/index.js:13:46)
15
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:1317:26
16
at parseClass (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn-private-methods/node_modules/acorn-private-class-elements/index.js:78:29)
17
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:839:17
18
at c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:749:23
19
at parse (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:552:15)
20
at parse (c:/Users/awheeler/Desktop/Imagine/imagine/node_modules/acorn/dist/acorn.js:575:35)
21
at c:/Users/awheeler/Desktop/Imagine/imagine/util/acornStyle.js:61:10
22
at c:/Users/awheeler/Desktop/Imagine/imagine/util/style.js:28:20
23
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.
Advertisement
Answer
The issue is with #a = 2
and not with #b() {}
.
This is because there are two separate modules for:
- methods: https://github.com/acornjs/acorn-private-methods
- class fields: https://github.com/acornjs/acorn-class-fields
So, add acton-class-fields
:
JavaScript
1
8
1
const { Parser } = require('acorn');
2
const privateMethods = require('acorn-private-methods');
3
const classFields = require('acorn-class-fields');
4
const MyParser = Parser
5
.extend(privateMethods)
6
.extend(classFields);
7
MyParser.parse('class X {#a =2; #b() {} }');
8