【问题标题】:Can I use ES6 Javascript in Node.js without Babel?我可以在没有 Babel 的 Node.js 中使用 ES6 Javascript 吗?
【发布时间】:2019-08-03 20:44:31
【问题描述】:

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

我刚刚在 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 代码吗?

【问题讨论】:

  • getCounter = () => { 在这种情况下,一开始就不是有效的 ES6
  • 但它是有效的Stage 3 Proposal - 您可以使用命令行标志--harmony在节点中启用它
  • @JaromandaX 是将该方法添加到Test.prototype 还是直接添加到该类的每个实例?
  • @JaromandaX 带有 --harmony 标志,它适用于箭头函数。
  • 是的,我知道@user2774480 ...但这仍然不是 ES6ES2015 (6th edition) ...它可能是ES2019 (10th edition) 或更高版本,因为它是不在ES2018 (9th edition) - ECMA 并没有在 2015 年停止开发 javascript ...自那以后又发布了 3 个规范

标签: javascript node.js ecmascript-6


【解决方案1】:

我可以在没有 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;
  }
}

无需为保持匿名箭头函数的唯一目的而创建属性。

【讨论】:

  • 类字段不是只能通过命令行标志启用吗? (提示:是的,他们是)
  • 好的,感谢您澄清这一点,我想我在某个地方的类中看到过这种箭头语法......但是您能否进一步澄清一下为什么类字段只能通过命令行标志启用?为什么我不能创建普通的类字段?
  • 因为它们是第 3 阶段提案 - 目前不在 ecma 规范中
  • 好的,谢谢你的信息,所以没有像 Java 这样的类变量?那么我将如何增加一个全局类计数器变量呢?
  • @Seblor - 我没有学究气......好吧,我是:D
【解决方案2】:

从 Nodejs 11.11.0 开始,类字段不是 ECMAscript 规范的一部分 .... 然而 .. 它们是第 3 阶段的提案

您可以通过使用--harmony 命令行参数启用一些(全部?)这些提议的功能

看看当前的游戏状态,类字段似乎也不是ES2019 (10th edition) 的一部分。虽然我找不到该文档(最多只能找到ES2018 (9th edition),但https://node.green/ 中的表格显示了标题为ESnext 的部分中的类字段,该部分位于ES2019 部分之后

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2017-11-08
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2013-04-03
    相关资源
    最近更新 更多