nodejs require vs es6 import

參考Using Node.js require vs. ES6 import/export node

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

There are technical difference 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.瀏覽器

這二者的區別async

  1. es6 import靜態引入,require能夠動態引入。
  • 有時候須要動態引入組件的時候就須要require了。
  1. 瀏覽器不支持es6 模塊化,因此 es6 import最後會被轉爲require 實現

第二個回答也基本上說明了這一點ide

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

  1. 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.
  1. 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.
相關文章
相關標籤/搜索