Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I specify es6 inside node js file

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
    }
}
like image 628
Shanimal Avatar asked Aug 13 '15 20:08

Shanimal


Video Answer


1 Answers

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.

like image 88
Paul Avatar answered Sep 21 '22 08:09

Paul