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?
Absolutely can and do use ES6 W/O babel. All major browsers support the vast majority of features natively (see CanIUse.com), in fact, the only major feature not supported is the import/export of modules. For these, you still have to manually import your modules in the correct order using script tags in the HTML.
Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.
If you've been active as a Node. js developer, or even dabbled in front-end libraries like React or Vue. js, then there's no doubt that you've likely run across Babel.
Using modern language features and browser APIs makes writing code easier, faster, and more fun. It also makes your code more maintainable. If you're happy writing ES5 and using XMLHttpRequest() , you definitely don't need Babel, but you might need some kind of therapy.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With