Module.exports and es6 Import

后端 未结 3 1799
再見小時候
再見小時候 2020-12-29 02:17

React with babel. I have this confusion with imports and module.exports. I assume babel when converting the ES6 code to ES5 converts the imports and exports to require and

3条回答
  •  一向
    一向 (楼主)
    2020-12-29 02:50

    When module.exports is not set it points to an empty object ({}). When you do module.exports = Tiger, you are telling the runtime the object being exported from that module is the Tiger object (instead of the default {}), which in this case is a function.
    Since you want to import that same function, the way to import is using the default import (import tiger from './tiger'). Otherwise, if you want to use named import (import { tiger } from './tiger') you must change the module.exports object or use export keyword instead of module.exports object.

    Default import/export:

    // tiger.js
    module.exports = tiger;
    // or
    export default function tiger() { ... }
    
    // animal.js
    import tiger from './tiger';
    

    Named import/export:

    // tiger.js
    module.exports = { tiger };
    // or
    module.exports.tiger = tiger
    // or
    export const tiger = () => { ... }
    // or
    export function tiger() => { ... }
    
    // animal.js
    import { tiger } from './tiger';
    

提交回复
热议问题