DEV Community

Cover image for Javascript's import vs require?
Christine Kim
Christine Kim

Posted on • Edited on

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

Top comments (3)

Collapse
 
buttercubz profile image
Erick Sosa Garcia

Also if you want to load a module dynamically, you can use the dynamic imports

const module = (await import("some_module")).default;

const { ... } = await import("some_module");
Enter fullscreen mode Exit fullscreen mode
Collapse
 
xtineskim profile image
Christine Kim

ooooh, I'm going to have to try this out! :)

Collapse
 
standelethan profile image
Ethan Standel

That's how you manage lazy loaded routes in React.