1300

In a project I am collaborating on, we have two choices on which module system we can use:

  1. Importing modules using require, and exporting using module.exports and exports.foo.
  2. Importing modules using ES6 import, and exporting using ES6 export

Are there any performance benefits to using one over the other? Is there anything else that we should know if we were to use ES6 modules over Node ones?

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
kpimov
  • 13,632
  • 3
  • 12
  • 18
  • 14
    `node --experimental-modules index.mjs` lets you use `import` without Babel and works in Node 8.5.0+. You can (and should) also [publish your npm packages as native ESModule](https://medium.com/@dandv/publishing-native-es-modules-with-node-v8-5-0-730736e0f612), with backwards compatibility for the old `require` way. – Dan Dascalescu Jan 26 '19 at 01:14
  • 1
    No necessary to use .mjs files, just use type: "module" in your package.json and put extension when importing only for your project files, that's it – Máxima Alekz May 24 '21 at 21:13

11 Answers11

960
Update

Since Node v12 (April 2019), support for ES modules is enabled by default, and since Node v15 (October 2020) it's stable (see here). Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module". The Node documentation has a ton more information, also about interop between CommonJS and ES modules.

Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end you have to run benchmarks to get a definite answer anyway.

ES modules can be loaded dynamically via the import() function. Unlike require, this returns a promise.


Previous answer

Are there any performance benefits to using one over the other?

Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts import and export declaration to CommonJS (require/module.exports) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.

There are technical differences between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.

Since ES6 modules are part of the standard, I would use them.

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 98
    @Entei: Seems like you want a default export, not a named export. `module.exports = ...;` is equivalent to `export default ...`. `exports.foo = ...` is equivalent to `export var foo = ...`; – Felix Kling Dec 19 '15 at 01:08
  • 15
    It's worth noting that even though Babel ultimately transpiles `import` to CommonJS in Node, used alongside Webpack 2 / Rollup (and any other bundler that allows ES6 tree shaking), it's possible to wind up with a file that is significantly smaller than the equivalent code Node crunches through using `require` exactly _because_ of the fact ES6 allows static analysis of import/exports. Whilst this won't make a difference to Node (yet), it certainly can if the code is ultimately going to wind up as a single browser bundle. – Lee Benson Nov 29 '16 at 19:17
  • 4
    ES6 Modules are in the latest V8 and are also arriving in other browsers behind flags. See: https://medium.com/dev-channel/es6-modules-in-chrome-canary-m60-ba588dfb8ab7 – Nexii Malthus May 25 '17 at 12:17
  • When would you not run your code in Node? Isn't most, if not all, JS these days using NPM, which uses node? – stackjlei Oct 04 '17 at 07:21
  • 4
    @stackjlei when it’s embedded in a website? Using npm doesn’t actually mean that the code is executed in node, thanks to module bundlers such as webpack. – Felix Kling Oct 04 '17 at 08:03
  • 1
    @FelixKling so CommonJS only comes for free if you're using a node server but not if you're using npm for Front End, right? – stackjlei Oct 06 '17 at 05:50
  • Is this answer still true in 2020? Any new updates? @Felix – Akhila Aug 11 '20 at 21:38
  • 2
    @Akhila: Added an update. Let me know if you think that suffices or if I should add more. Thank you for pinging me about this. – Felix Kling Aug 12 '20 at 07:35
  • doesn't work: my node program says **SyntaxError: Cannot use import statement outside a module** when trying **import { countryList } from './countries.mjs'** – SuperUberDuper Sep 01 '22 at 14:27
  • @SuperUberDuper Seems like the file that contains this line isn't recognized as module. Does it have an `.mjs` extensions or does the closest `package.json` file contain `"type": "module"`? See https://nodejs.org/api/packages.html#determining-module-system – Felix Kling Sep 01 '22 at 15:48
  • @FelixKling Yes it has mjs but not package.json If i add to package, it works, but i prefer not to do that – SuperUberDuper Sep 01 '22 at 16:00
  • @FelixKling I have a question from a different point of view, can you take a look ? https://stackoverflow.com/questions/74690087/what-is-the-problem-of-mixing-require-and-import-in-the-same-typescript-file – Qiulang Dec 06 '22 at 03:39
228

There are several usage / capabilities you might want to consider:

Require:

  • 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.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • 24
    What makes you think ES6 imports are asynchronous? – Felix Kling Jul 11 '15 at 12:56
  • 5
    @FelixKling - combination of various observations. Using JSPM (ES6 Module Loader...) I noticed that when an import modified the global namespace the effect isn't observed inside other imports (because they occur asynchronously.. This can also be seen in transpiled code). Also, since that is the behavior (1 import doesn't affect others) there no reason not to do so, so it could be implementation dependant – Amit Jul 11 '15 at 13:06
  • 41
    You mention something very important: module loader. While ES6 provides the import and export syntax, it does not define how modules should be loaded. The important part is that the declarations are statically analyzable, so that dependencies can be determined without executing the code. This would allow a module loader to either load a module synchronously or asynchronously. But ES6 modules by themselves are not synchronous or asynchronous. – Felix Kling Jul 11 '15 at 14:18
  • 5
    @FelixKling ES6 module loader was tagged in the OP so I assume it makes it relevant to the answer. Also I stated that based on observations async is current behavior, as well as possibility in the future (in any implementation) so it's a relevant point to consider. Do you think it's wrong? – Amit Jul 11 '15 at 14:23
  • 12
    I think it's important not to conflate the module system/syntax with the module loader. E.g if you develop for node, then you are likely compiling ES6 modules to `require` anyway, so you are using Node's module system and loader anyway. – Felix Kling Jul 11 '15 at 14:27
  • @Amit My mistake. I'm using Babel, not ES6-module-loader – kpimov Jul 12 '15 at 07:28
  • 1
    @kpimov That's fine. I modified the answer anyway after Felix Kling's comments. The async part is not guarenteed to be available (implementation dependant), but possibly will be used. – Amit Jul 12 '15 at 08:17
  • 1
    @FelixKling - Douglas Crockford in his talk 'The better parts' https://youtu.be/_EF-FO63MXs?t=764 seemed to indicate that the ES6 module imports would be fully asynchronous. – Doug Coburn May 28 '17 at 23:03
  • This answer helped me understand much better, thanks @Amit! – Steve Bauman Sep 06 '17 at 15:04
  • @Amit can you clarify "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)." VS asynchronous module loading in es6 modules? – dragonmnl Sep 15 '17 at 14:57
  • While require allows dynamic loading, when you use ES6 imports, webpack does tree-shaking and eliminates code which is not being used. – prgmrDev Nov 18 '18 at 08:44
  • The major difference between require and import , is that require will automatically scan node_modules to find modules, but import , which comes from ES6, won't. Most people use babel to compile import and export , which makes import act the same as require – Michael Jul 01 '19 at 01:47
  • I think an async loader with the presence of a top-level await is a smart thing to do. For example, something like const pkg = pkgload. And if it can easily be determined where the first call/calls are, await there. Or somewhere nearby. Till then, no need to halt the codes. Of course, the implementation might not be easy so maybe they use something like Promise.all(...) instead. (This is probably not how things work and I am just theorizing in this case) – pratikpc Sep 25 '20 at 21:10
133

As of right now ES6 import, export is always compiled to CommonJS, so there is no benefit using one or other. Although usage of ES6 is recommended since it should be advantageous when native support from browsers released. The reason being, you can import partials from one file while with CommonJS you have to require all of the file.

ES6 → import, export default, export

CommonJS → require, module.exports, exports.foo

Below is common usage of those.

ES6 export default

// hello.js
function hello() {
  return 'hello'
}
export default hello

// app.js
import hello from './hello'
hello() // returns hello

ES6 export multiple and import multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
export { hello1, hello2 }

// app.js
import { hello1, hello2 } from './hello'
hello1()  // returns hello1
hello2()  // returns hello2

CommonJS module.exports

// hello.js
function hello() {
  return 'hello'
}
module.exports = hello

// app.js
const hello = require('./hello')
hello()   // returns hello

CommonJS module.exports multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
module.exports = {
  hello1,
  hello2
}

// app.js
const hello = require('./hello')
hello.hello1()   // returns hello1
hello.hello2()   // returns hello2
Hasan Sefa Ozalp
  • 6,353
  • 5
  • 34
  • 45
  • 8
    You actually can use `Object Destructuring` when using CommonJS require as well. So you could have: `const { hello1, hello2 } = require("./hello");` and it will be **somewhat** similar to using import/export. – Petar Sep 15 '20 at 09:08
  • 10
    This is by far the best answer as it provides not only the description, but also the actual code snippets. – IvanD Apr 14 '21 at 17:55
48

The main advantages are syntactic:

  • More declarative/compact syntax
  • ES6 modules will basically make UMD (Universal Module Definition) obsolete - essentially removes the schism between CommonJS and AMD (server vs browser).

You are unlikely to see any performance benefits with ES6 modules. You will still need an extra library to bundle the modules, even when there is full support for ES6 features in the browser.

snozza
  • 2,123
  • 14
  • 17
  • 4
    Could you clarify why one needs a bundler even when browsers has full ES6 module support? – E. Sundin Jul 03 '16 at 15:15
  • 1
    Apologies, edited to make more sense. I meant that the import/export modules feature is not implemented in any browsers natively. A transpiler is still required. – snozza Jul 04 '16 at 09:23
  • 18
    It seems a bit contradictory frased to me. If there is **full support** then what is the purpose of the bundler? Is there something missing in the ES6 spec? What would the bundler actually do that isn't available in a **fully supported environment**? – E. Sundin Jul 04 '16 at 22:14
  • 1
    As @snozza said..."the import/export modules feature is not implemented in any browsers naively. A transpiler is still required" – robertmain Oct 13 '17 at 01:35
  • As I understand it, ES6 browser support now means you can use the simpler JavaScript module syntax (`export` and `import`) natively in [most modern browsers](https://www.caniuse.com/#feat=es6-module). Unless you still need to write for IE9. Correct me if I've missed something glaringly obvious, but I can use ES6 modules (say) in Chrome running node's http-server with no other library. – Dave Everitt Jun 26 '18 at 20:33
  • 3
    You no longer need any extra libraries. Since v8.5.0 (released more than a year ago), `node --experimemntal-modules index.mjs` lets you use `import` without Babel. You can (and should) also [publish your npm packages as native ESModule, with backwards compatibility](https://medium.com/@dandv/publishing-native-es-modules-with-node-v8-5-0-730736e0f612) for the old `require` way. Many browsers also support [dynamic imports](https://developers.google.com/web/updates/2017/11/dynamic-import) natively. – Dan Dascalescu Sep 26 '18 at 03:33
39

Are there any performance benefits to using one over the other?

The current answer is no, because none of the current browser engines implements import/export from the ES6 standard.

Some comparison charts http://kangax.github.io/compat-table/es6/ don't take this into account, so when you see almost all greens for Chrome, just be careful. import keyword from ES6 hasn't been taken into account.

In other words, current browser engines including V8 cannot import new JavaScript file from the main JavaScript file via any JavaScript directive.

( We may be still just a few bugs away or years away until V8 implements that according to the ES6 specification. )

This document is what we need, and this document is what we must obey.

And the ES6 standard said that the module dependencies should be there before we read the module like in the programming language C, where we had (headers) .h files.

This is a good and well-tested structure, and I am sure the experts that created the ES6 standard had that in mind.

This is what enables Webpack or other package bundlers to optimize the bundle in some special cases, and reduce some dependencies from the bundle that are not needed. But in cases we have perfect dependencies this will never happen.

It will need some time until import/export native support goes live, and the require keyword will not go anywhere for a long time.

What is require?

This is node.js way to load modules. ( https://github.com/nodejs/node )

Node uses system-level methods to read files. You basically rely on that when using require. require will end in some system call like uv_fs_open (depends on the end system, Linux, Mac, Windows) to load JavaScript file/module.

To check that this is true, try to use Babel.js, and you will see that the import keyword will be converted into require.

enter image description here

prosti
  • 42,291
  • 14
  • 186
  • 151
  • 2
    Actually, there's one area where performance *could* be improved -- bundle size. Using `import` in a Webpack 2 / Rollup build process can potentially reduce the resulting file size by 'tree shaking' unused modules/code, that might otherwise wind up in the final bundle. Smaller file size = faster to download = faster to init/execute on the client. – Lee Benson Nov 29 '16 at 19:12
  • 2
    the reasoning was no current browser on the planet earth allows the `import ` keyword natively. Or this means you cannot import another JavaScript file from a JavaScript file. This is why you cannot compare performance benefits of these two. But of course, tools like Webpack1/2 or Browserify can deal with compression. They are neck to neck: https://gist.github.com/substack/68f8d502be42d5cd4942 – prosti Nov 29 '16 at 19:46
  • 4
    You're overlooking 'tree shaking'. Nowhere in your gist link is tree shaking discussed. Using ES6 modules enables it, because `import` and `export` are static declarations that import a specific code path, whereas `require` can be dynamic and thus bundle in code that's not used. The performance benefit is indirect-- Webpack 2 and/or Rollup can _potentially_ result in smaller bundle sizes that are faster to download, and therefore appear snappier to the end user (of a browser). This only works if all code is written in ES6 modules and therefore imports can be statically analysed. – Lee Benson Nov 30 '16 at 10:46
  • 2
    I updated the answer @LeeBenson, I think if we consider the native support from browser engines we cannot compare yet. What comes as handy three shaking option using the Webpack, may also be achieved even before we set the CommonJS modules, since for most of the real applications we know what modules should be used. – prosti Dec 05 '16 at 21:57
  • 1
    Your answer is totally valid, but I think we're comparing two different characteristics. _All_ `import/export` is converted to `require`, granted. But what happens _before_ this step could be considered "performance" enhancing. Example: If `lodash` is written in ES6 and you `import { omit } from lodash`, the ultimate bundle will ONLY contain 'omit' and not the other utilities, whereas a simple `require('lodash')` will import everything. This will increase the bundle size, take longer to download, and therefore decrease performance. This is only valid in a browser context, of course. – Lee Benson Dec 06 '16 at 07:42
  • _"since for most of the real applications we know what modules should be used"_ - that's true for your own modules, but when importing packages from npm, you probably don't know much about the internals. If the source is written using ES6 import/export, and you only include what you _know_ you need, Webpack 2/Roll up can often omit what you don't need because it can statically analyse the source before transpiling. Again, I'm talking about situations where the target is a browser bundle and you care about the size of that bundle. I've had 5mb+ reduced to 500kb in practice. – Lee Benson Dec 06 '16 at 07:43
  • We are on the same page, `import` notation is handy and allows you to be more specific, which bundlers like. I cannot point at the moment to any tool that would do *three shaking* thing for the CommonJS modules that are not loaded dynamically. But I imagine this is possible via statical analysis of the code in use. – prosti Dec 06 '16 at 08:27
  • This answer is out of date. [All modern browsers](https://caniuse.com/#feat=es6-module) support `import`, and Chrome&Safari also support [dynamic imports](https://developers.google.com/web/updates/2017/11/dynamic-import) natively. – Dan Dascalescu Sep 26 '18 at 03:35
38

Using ES6 modules can be useful for 'tree shaking'; i.e. enabling Webpack 2, Rollup (or other bundlers) to identify code paths that are not used/imported, and therefore don't make it into the resulting bundle. This can significantly reduce its file size by eliminating code you'll never need, but with CommonJS is bundled by default because Webpack et al have no way of knowing whether it's needed.

This is done using static analysis of the code path.

For example, using:

import { somePart } 'of/a/package';

... gives the bundler a hint that package.anotherPart isn't required (if it's not imported, it can't be used- right?), so it won't bother bundling it.

To enable this for Webpack 2, you need to ensure that your transpiler isn't spitting out CommonJS modules. If you're using the es2015 plug-in with babel, you can disable it in your .babelrc like so:

{
  "presets": [
    ["es2015", { modules: false }],
  ]
}

Rollup and others may work differently - view the docs if you're interested.

Lee Benson
  • 11,185
  • 6
  • 43
  • 57
32

When it comes to async or maybe lazy loading, then import () is much more powerful. See when we require the component in asynchronous way, then we use import it in some async manner as in const variable using await.

const module = await import('./module.js');

Or if you want to use require() then,

const converter = require('./converter');

Thing is import() is actually async in nature. As mentioned by neehar venugopal in ReactConf, you can use it to dynamically load react components for client side architecture.

Also it is way better when it comes to Routing. That is the one special thing that makes network log to download a necessary part when user connects to specific website to its specific component. e.g. login page before dashboard wouldn't download all components of dashboard. Because what is needed current i.e. login component, that only will be downloaded.

Same goes for export : ES6 export are exactly same as for CommonJS module.exports.

NOTE - If you are developing a node.js project, then you have to strictly use require() as node will throw exception error as invalid token 'import' if you will use import . So node does not support import statements.

UPDATE - As suggested by Dan Dascalescu: Since v8.5.0 (released Sep 2017), node --experimental-modules index.mjs lets you use import without Babel. You can (and should) also publish your npm packages as native ESModule, with backwards compatibility for the old require way.

See this for more clearance where to use async imports - https://www.youtube.com/watch?v=bb6RCrDaxhw

Joel
  • 249
  • 2
  • 10
Meet Zaveri
  • 2,921
  • 1
  • 22
  • 33
19

The most important thing to know is that ES6 modules are, indeed, an official standard, while CommonJS (Node.js) modules are not.

In 2019, ES6 modules are supported by 84% of browsers. While Node.js puts them behind an --experimental-modules flag, there is also a convenient node package called esm, which makes the integration smooth.

Another issue you're likely to run into between these module systems is code location. Node.js assumes source is kept in a node_modules directory, while most ES6 modules are deployed in a flat directory structure. These are not easy to reconcile, but it can be done by hacking your package.json file with pre and post installation scripts. Here is an example isomorphic module and an article explaining how it works.

isysd
  • 371
  • 2
  • 4
11

I personally use import because, we can import the required methods, members by using import.

import {foo, bar} from "dep";

FileName: dep.js

export foo function(){};
export const bar = 22

Credit goes to Paul Shan. More info.

chandoo
  • 1,276
  • 2
  • 21
  • 32
3
  • ES modules are static, which means that imports are described at the top level of every module and outside any control flow statement. This will not work:

    if (condition) {
       import module1 from 'module1'
    }
    

But it in commonjs, it is allowed:

if (condition) {
    module = require('module1')
}
  • ES modules run implicitly in strict mode. This means that we don't have to explicitly add the "use strict" statements at the beginning of every file. Strict mode cannot be disabled; therefore, we cannot use undeclared variables or the with statement or have other features that are only available in non-strict mode. strict mode is a safer execution mode.

  • In ESM, some important CommonJS references are not defined. These include require , exports , module.exports , __filename, and __dirname.

  • We can import CommonJS modules from ESM by using the standard import syntax. But only default exports work:

       import packageName from 'commonjs-package' // Works
      import { moduleName } from 'commonjs-package' // Errors
    

But, it is not possible to import ES modules from CommonJS modules.

  • ESM cannot import JSON files directly as modules, a feature that is used quite frequently with CommonJS. That is why in reactjs fetch api is used.

    import data from './data.json' //fails
    
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
2

Not sure why (probably optimization - lazy loading?) is it working like that, but I have noticed that import may not parse code if imported modules are not used.
Which may not be expected behaviour in some cases.

Take hated Foo class as our sample dependency.

foo.ts

export default class Foo {}
console.log('Foo loaded');

For example:

index.ts

import Foo from './foo'
// prints nothing

index.ts

const Foo = require('./foo').default;
// prints "Foo loaded"

index.ts

(async () => {
    const FooPack = await import('./foo');
    // prints "Foo loaded"
})();

On the other hand:

index.ts

import Foo from './foo'
typeof Foo; // any use case
// prints "Foo loaded"
l00k
  • 1,525
  • 1
  • 19
  • 29