在运行时在模块中启用V8中的Harmony ES6功能?

时间:2013-10-17 21:03:32

标签: node.js v8 ecmascript-harmony

Node v0.10.20提供了许多与和声相关的选项,

--harmony_typeof (enable harmony semantics for typeof)
--harmony_scoping (enable harmony block scoping)
--harmony_modules (enable harmony modules (implies block scoping)
--harmony_proxies (enable harmony proxies)
--harmony_collections (enable harmony collections (sets, maps, and weak maps))
--harmony (enable all harmony features (except typeof))

我知道这些不是生产就绪的功能,而且它们正在开发中,但其中很多都足够好。

有没有办法在运行时启用它们?

"use strict";
"use harmony collections";

像上面这样的东西。即使它不仅仅是模块级别启用这些功能,最好确保它们在模块内部启用,而不是假设它们已被启用。

3 个答案:

答案 0 :(得分:10)

不,你不能。事实上,如果你试图在同一个V8实例中偷偷进入这些标志的多个不同设置,那么在V8内部可能会出现一些可能错误的事情(披露:我实现了大部分这些标志)。

答案 1 :(得分:1)

没有办法做到这一点,解释器读取模块的内容然后验证它们然后评估它们。如果您将使用某些ES6特定语法,则验证将失败,并且不会评估代码。

您只能隔离ES6语法文件并将其作为子进程运行(带有必要的选项),但我想这不是您想要的方式。

答案 2 :(得分:1)

对于一个模块(在exec /子进程中隔离ES6文件),前面的答案并不是一个坏主意,如果你能够处理它在子进程中运行的想法。

最好看的答案是,如果你是一个模块,你需要这些功能的文档,并在运行时测试它们并保留一个有用的错误。我还没有弄清楚如何很好地测试这个(让我休息一下,我已经使用节点3天了)

如果您正在撰写应用,答案略有不同。在我的情况下,我正在编写的应用程序可能会使用这些功能 - 并且由于只能在shebang行中使用单个参数的限制,因此无法在运行时更改JS版本(其中,当然,如上所述,完全有道理,并且不想执行子进程(我的服务器已经是多线程) - 我被迫编写一个脚本来运行我的节点服务器,这样我的用户就不用了超出正确的节点命令行来运行我的应用程序(丑陋)如果我想使用超过--harmony"use strict";我可以使用脚本,因为它只是一个调用节点的shell脚本和我的应用..

建议使用#!/usr/bin/env node作为shebang(无论在哪里安装,都会为您找到节点)但是,您只能在shebang中使用一个参数,因此这不适用于{{ 1}}(或任何其他参数)

当然 - 你总是可以运行--harmony,但是如果你需要某些选项,你每次都要输入它,因此建议使用shell脚本(由我!)。我想你可以在你的模块中包含这个(或者这样的)脚本,并推荐它用于执行使用你的模块的应用程序。

这是我用于服务器的shell脚本的类似实现,它将找到节点并使用您需要的任何参数运行脚本:

node --harmony --use_strict --blah_blah yourScript.js

值得注意的是,如果你只想使用和谐和严格,虽然你不能在一个shebang中指定两者,你可以硬编码节点的位置并使用“use strict”;别名:

#!/bin/bash

if [ "$myScript" == "" ]; then
  myScript="./src/myNodeServer.js"
fi

if [ "$myNodeParameters" == "" ]; then
  myNodeParameters="--harmony --use_strict"
fi

if [ "$myNode" = "" ]; then
    myNode=`which node`
fi

if [ "$myNode" = "" ]; then
    echo node was not found! this app requires nodeJS to be installed in order to run.
    echo if you have nodeJS installed but is not found, please make sure the 'which'
    echo command is available. alternatively, you can forcibly specify the location of
    echo node with the $myNode environment variable, or editing this file.
else
    echo Yay! node binary was found at $myNode
fi

if [ "$1" = "start" ]; then 
  echo you asked to start..
  echo calling $myNode $myParameters $myScript $2
  $myNode $myParameters $myScript $2
  exit 
elif [ "$1" = "-h" ] || [ "$1" = "--help" ]; then 
  echo you asked for help..
  echo usage:
  echo $0 start [script.js] [parameters for script]
  echo parameters for node and node location can be
  echo set with the \$myParameters and \$myNode env
  echo variables (or edit the top of this file).
  exit
else 
  echo no valid command specified - use $0 --help to see help.
fi