Using Node.js require vs. ES6 import/export

后端 未结 10 911
醉酒成梦
醉酒成梦 2020-11-22 05:19

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

  1. Importing modules using require, and exporting using
10条回答
  •  一生所求
    2020-11-22 05:23

    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.

提交回复
热议问题