Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use es6 style module import in nodejs application

I am using the latest nodejs version, but am still getting an error while using es6 module import.

I could also find on a blog that node doesn't yet support es6 import module. https://nodesource.com/blog/es-modules-and-node-js-hard-choices/ - no JavaScript runtime currently supports ES Modules. I am new to javascript and node, is anyone using es6 module import with nodejs, without transpiling the code to lower js versions.

like image 519
vashishth Avatar asked Dec 02 '22 13:12

vashishth


1 Answers

You can if you are willing to use a tool like Babel.

npm i -D babel babel-cli babel-core babel-preset-es2015

Create a file .babelrc and put the following in it:

{
    "presets": ["es2015"]
}

And then in package.json in the scripts section do some thing like this:

"dev": "babel src -d dist && node dist/your_file.js"

This will transpile all of the code in a directory named src/ but it in a directory called dist/, and then run the file you specify.

It can then be used via the command as follows:

npm dev
like image 53
Matt Altepeter Avatar answered Jan 17 '23 18:01

Matt Altepeter