Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute es6 scripts from CLI

Tags:

I have the latest NodeJS installed and for any JavaScript files, I can execute it with node myscript.js but recently I'm learning es6 and for some of the latest syntax, it just pop out some errors/exceptions while executing. I tried babel-cli, but didn't seem to work as it is for compile es6 to 5 not for command line execute.

like image 919
photosynthesis Avatar asked Apr 05 '16 05:04

photosynthesis


People also ask

How do you run JavaScript script through the terminal?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.

How do I run a node JS command line?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.


1 Answers

1) To enable the support of ES6, use the --harmony flag:

node --harmony myscript.js 

This will enable the available ES6 syntax in node. But notice it's currently a limited subset of the ES6 standard (see the compatibility table).

2) To have a complete compatibility, you have to use babel node.
Install @babel/node to get a babel-node executable which works exactly the same as Node.js's CLI, only it will compile ES6 code before running it.

babel-node myscript.js 
like image 198
Dmitri Pavlutin Avatar answered Sep 21 '22 12:09

Dmitri Pavlutin