Using Node.js require vs. ES6 import/export

后端 未结 10 915
醉酒成梦
醉酒成梦 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

    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
    

提交回复
热议问题