In Nodejs is the statement import Obj from 'module_1'
the same as const Obj = require('module_1')
? This is when Obj is supposed to be a Constructor. I want to know because using the import statement does not seem to work for me so I was wondering if there was an alternative way of writing it.
Asked
Active
Viewed 9,427 times
6

Ikim SS
- 139
- 2
- 8
-
yes. node js uses common js module format and need to use require – sridhar.. Feb 19 '19 at 08:40
-
As I understand it, the es6 import feature is available in NodeJS natively only through a special flag. More details in a similar SO question [here](https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node/50641589#50641589). TLDR; Use experimental flag or a transpiler like Babel – Chirag Ravindra Feb 19 '19 at 08:44
-
Possible duplicate of [How can I use an es6 import in node?](https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node) – Chirag Ravindra Feb 19 '19 at 08:44
-
2Possible duplicate of [Using Node.js require vs. ES6 import/export](https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export) – Andreas Feb 19 '19 at 08:47
2 Answers
1
Import and require cannot both be used. You can either use require without installing/modifying anything or you can use imports only and adding "type": "module", to your package.json file. They say you have to make your server.js file's extension as .mjs but .js works for me. This is if you want to use both import and require: https://www.kindacode.com/article/node-js-how-to-use-import-and-require-in-the-same-file/

hithaaaa
- 11
- 2
-1
There is no JavaScript engine yet that natively supports ES6 modules. import is available for ES6 Module and require is for ES5. Nodejs support ES5 so it uses require... To Use import and other feature of ES6 make use of babel which converts the commomjs code to ES5 More details for ES6 and ES6

Rohan Shukla
- 533
- 1
- 4
- 16
-
3Downvote because this answer was lifted (with similar wording) from https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export. – Switch386 Apr 01 '20 at 06:02
-
3Don't most modern browsers now support ES6 and thus ES6 modules, or am I mistaken here? also, you should make a distinction between Node.js and browser JS engines -- require isn't natively supported in ES5 in browsers :) – Prid Sep 08 '21 at 19:52
-
1When this answer was written, only the now dead Internet Explorer didn't have native support for ES6 modules (although Node.js had it locked behind a flag until the end of the year). – Quentin Jun 29 '23 at 14:55