首页 > 解决方案 > 我可以在没有 Babel 的 Node.js 中使用 ES6 Javascript 吗?

问题描述

我只是想知道,是否可以在 2019 年的 Node 10.15 中使用 ES6,因为我认为,ES6 现在将成为原生支持和实现的 Javascript 功能?我在这里找到了一些答案:NodeJS 计划支持导入/导出 es6 (es2015) 模块 ,但我不确定现在的实际状态。

我刚刚在 Node 中尝试了一些带有箭头函数的 ES6 类:

 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;
     }
 }

我收到一个错误:

     getCounter = () => {
                ^

SyntaxError: Unexpected token =

而且,我无法创建对类来说是全局的类实例变量(并且每次创建新的类实例时都会将 testVar 增加 1..)在 Javascript 类中通常是如何完成的?

我知道有一个 babel 编译器包支持这个并以某种方式转换代码,但是现在 ES6 不应该是原生支持的 Javascript 代码吗?

标签: javascriptnode.jsecmascript-6

解决方案


我可以在没有 Babel 的 Node.js 中使用 ES6 Javascript 吗?

是的,你可以,Node 支持 ES2018 之前的所有 JS (ECMAScript) 功能: https ://node.green/

你应该像这样创建你的方法:

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;
  }
}

无需仅出于持有匿名箭头函数的目的而创建属性。


推荐阅读