Search code examples
javascriptnode.jsclassstatic

Static constructor gives syntax error in NodeJS


I've been looking at this error for a long time and I just cannot wrap my head around it.

Here's the code:

class Instance {

    static {

    }

}

module.exports = Instance;

That is all there is. The class was full of stuff but I deleted them all because they are irrevelant. It's giving the same error with or without them.

The error:

    static {
           ^

SyntaxError: Unexpected token '{'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (path\to\project\index.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

I've used static constructors in the past and testing the same code somewhere else seems to work so I dont understand what the issue is here. Please help me.

SOLUTION: Updated Node to 16.13.1 and it now works. 16.7.0 wasnt enough.


Solution

  • It is supported by Node 17.3.0. It is an ES2022 feature. This https://node.green/#ES2022 is a nice link to find ES feature compatibility in Nodejs. You will have to download the current version of Nodejs which is 17.3.0. enter image description here