29-05-2021 Import vs require in ES6

I was recently creating a script that requested data from a 3rd party API, and I was running this script within the server of a Sapper project. In order to correctly get this data, I went through promise chaining, and I had to use an '.mjs' extension on my script.
Since Node v12, ES modules has been enabled by default. Hence my use of '.mjs' to run my file including a node module.Another way to resolve this issue is to use import with Node.js, you have to edit the package.json to 'type':'module'. However, using this caused my Sapper server to crash since it wasn't supported, as the rollup file outputs the format to commonjs.
Commonjs uses require and module.exports, while ES6 uses import and export. Import and Export are used to refer to an ES module, and can't be used with other file types.
Reading a little more up on it, here are some differences I found
  • import will be run in the beginning of the file, always, whereas require can be called anytime and anywhere
  • import gets sorted to the top of the file
  • import can be used to selectively load parts you need, and can save memory
  • import can be asynchronous, which apparently perform better, and require is synchronous