Javascript's import vs require?

xtineskim

Christine Kim

Posted on May 28, 2021

Javascript's import vs require?

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 Explained in (this GitHub issue).

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

Are there any others that I missed?
tl;dr: ES6 -> import, export default, export vs commonjs -> require, module.exports, export.foo

💖 💪 🙅 🚩
xtineskim
Christine Kim

Posted on May 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related