Using Node.js require vs. ES6 import/export

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

  • Importing modules using require , and exporting using module.exports and exports.foo .
  • 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?


    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 difference between CommonJS and ES6 modules, eg 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.


    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 require s, 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.


    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.

    链接地址: http://www.djcxy.com/p/52196.html

    上一篇: 不能使用String.Empty作为可选参数的默认值

    下一篇: 使用Node.js需要与ES6导入/导出