Using Node.js require vs. ES6 import/export

后端 未结 10 773
醉酒成梦
醉酒成梦 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:34

    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"
    

提交回复
热议问题