7

In order to use es6, we pass the harmony flag in the command line

node --harmony myscript.js

Is there a way to do this from inside the file, such as use harmony?

#! /usr/bin/node
use harmony

class MyScript {
    constructor (options) {
        this.options = options;
    }
    get options () {
        return this.options
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Shanimal
  • 11,517
  • 7
  • 63
  • 76

1 Answers1

4

If your intention is to do this just so that you can run the script directly like ./myscript.js you could use this:

#!/bin/sh
':' //; exec node --harmony "$0" "$@";

class MyScript {
    constructor (options) {
        this.options = options;
    }
    get options () {
        return this.options
    }
}

I got the polyglot trick from the blog Obscure Javascript.

If your intention is to be able to have another script started without --harmony be able to require this script, then this trick will not work.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • I wanted to be able to require es6 scripts, so I think as long as my initial file uses this trick it should work fine. – Shanimal Aug 13 '15 at 21:02
  • 1
    @Shanimal Yeah, as long as the entry point starts node with `--harmony` every script required from their will be using it. – Paul Aug 13 '15 at 21:11
  • Looks like `#! /usr/bin/node --harmony` also works. Is there a difference? – Shanimal Aug 13 '15 at 21:36
  • @Shanimal Nice solution. That will [usually break](http://stackoverflow.com/a/4304187/772035) if you ever want to specify more than one argument, but for your case I would still use it. It's a lot nicer. If you do use, it you should write it as an answer to your question and accept your own answer. – Paul Aug 14 '15 at 00:13