MarcL
MarcL

Reputation: 3593

Can I use ES6 Javascript in Node.js without Babel?

I was just wondering, if it's possible to use ES6 in Node 10.15 now in 2019, because I thought, ES6 would now be a natively supported and implemented Javascript feature? I found some answer here: NodeJS plans to support import/export es6 (es2015) modules but I wasnt sure what the actual status is now.

I just tried out some ES6 classes with arrow functions in Node:

 class Test {
     testVar = 1;
     constructor(x,y) {
        this.counter =0;
        this.x = x;
        this.y = y;
        this.increaseCounter();
        this.testVar +=1;
     }

     getCounter = () => {
        console.log("Counter:", this.counter);
     }

     increaseCounter = () => {
        this.counter += 1;
     }
 }

I get an error:

     getCounter = () => {
                ^

SyntaxError: Unexpected token =

and also, I cannot create class instance variables that are global to the class (and increase testVar by 1 every time a new class instance is created..) How is that normally done in Javascript classes?

I know there is a babel compiler package out there that supports this and transpiles the code somehow, but should ES6 not be natively supported Javascript code by now?

Upvotes: 9

Views: 5870

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

as of Nodejs 11.11.0, class fields are not part of the ECMAscript spec .... yet .. they are a stage 3 proposal

You can enable some (all?) of such proposed features by using the --harmony command line argument

Looking at the current state of play, class fields don't seem to be part of ES2019 (10th edition) either. Whilst I can't find that document (can only find up to ES2018 (9th edition), the table in https://node.green/ shows class fields in a section titled ESnext which is after the section ES2019

Upvotes: 0

Seblor
Seblor

Reputation: 7136

Can I use ES6 Javascript in Node.js without Babel?

Yes, you can, Node supports all JS (ECMAScript) features up to ES2018 : https://node.green/

You should create your methods like this :

class Test {
  testVar = 1;
  constructor(x, y) {
    this.counter = 0;
    this.x = x;
    this.y = y;
    this.increaseCounter();
    this.testVar += 1;
  }

  getCounter() {
    console.log("Counter:", this.counter);
  }

  increaseCounter() {
    this.counter += 1;
  }
}

No need to create an attribute for the only purpose being holding an anonymous arrow function.

Upvotes: 4

Related Questions