3

When including packages in JavaScript when would I want to use import vs. require? Are they the same or do they have distinct use cases?

  • 2
    Possible duplicate of [Using Node.js require vs. ES6 import/export](https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export) – Durga Jul 17 '18 at 05:41
  • Possible duplicate of [what is the difference between import and const and which is preferred in commonjs](https://stackoverflow.com/questions/34601582/what-is-the-difference-between-import-and-const-and-which-is-preferred-in-common) – Nazim Kerimbekov Jul 17 '18 at 05:42

1 Answers1

1

You can have dynamic loading where the loaded module name isn't predefined /static, or where you conditionally load a module only if it's "truly required" (depending on certain code flow). Loading is synchronous. That means if you have multiple requires, they are loaded and processed one by one. ES6 Imports:

You can use named imports to selectively load only the pieces you need. That can save memory. Import can be asynchronous (and in current ES6 Module Loader, it in fact is) and can perform a little better. Also, the Require module system isn't standard based. It's is highly unlikely to become standard now that ES6 modules exist. In the future there will be native support for ES6 Modules in various implementations which will be advantageous in terms of performance.

Sowdhanya
  • 63
  • 4