Reputation: 443
I'm new to nodejs. I see we are using
const http = require('http')
instead of import . I found of that is because nodejs is older than es6
why node uses require not import?
However, I can use arrow functions. which is es6. how it is possible?
Thanks
Upvotes: 1
Views: 403
Reputation: 897
It's finally happened: nearly 4 years after the import keyword was introduced in ES6, Node.js introduced experimental support for ES6 imports and exports. In Node.js 12, you can use import and export in your project if you do both of the below items.
1) Add the --experimental-modules
flag when running Node.js
2) Use the .mjs
extension or set "type": "module"
in your package.json.
This package.json is very important. The type: "module" property tells Node.js to treat .js files as ESM modules. In other words, {"type":"module"}
tells Node.js to expect import and export statements in .js files.
You can run file like this
node --experimental-modules index.js
Upvotes: 3