zoukankan      html  css  js  c++  java
  • module.exports与exports,export与export default之间的关系和区别

     module.exports    

     

    CommonJS   
     - require    

    每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(即module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性。

    // a1.js
    const Programmer = {
        name: 'a.js'
    }
    module.exports = {
        Programmer
    }
    console.log(module)
    // b.js
    let Programmer = require('./a1.js')
    console.log('b----------', Programmer)
    console.log('b----------', Programmer.name)
    Module {
      id: 'D:\pengfei\learn\设计模式\project\a1.js',
      path: 'D:\pengfei\learn\设计模式\project',
      exports: { Programmer: { name: 'a.js', age: '25' }, add: [Function: add] },
      parent: Module {...},
      filename: 'D:\pengfei\learn\设计模式\project\a1.js',
      loaded: false,
      children: [],
      paths: [...]
    }
    b---------- { Programmer: { name: 'a.js', age: '25' }, add: [Function: add] }
    b---------- undefined
    exports

    Node为每个模块提供一个exports变量,指向module.exports。这等同在每个模块头部,有一行这样的命令。

    var exports = module.exports;
    

    直接在 exports 对象上添加方法,表示对外输出的接口,如同在module.exports上添加一样。

    * 因为 Node 模块是通过 module.exports 导出的,如果直接将exports变量指向一个值,就切断了exports与module.exports的联系,导致意外发生

    // a2.js
    const Programmer = {
        name: 'a.js'
    }
    const add = function (value) {
    return value + x;
    };
    exports = {
        Programmer,
        add
    }
    // exports.Programmer = Programmer
    // exports.add = add
    console.log(module)
    Module {
      id: 'D:\pengfei\learn\设计模式\project\a2.js',
      path: 'D:\pengfei\learn\设计模式\project',
      exports: {},
      parent: Module {...},
    ...
    } b---------- {} b---------- undefined
    export

    ES6

     - import 

    // profile.js
    var firstName = 'Michael';
    var lastName = 'Jackson';
    var year = 1958;
    
    export {firstName, lastName, year};

    注意,export命令规定的是对外的接口,必须与模块内部的变量建立一一对应关系

    // 写法一
    export var m = 1;
    
    // 写法二
    var m = 1;
    export {m};
    
    // 写法三
    var n = 1;
    export {n as m};
    export default

    export default命令,为模块指定默认输出

    export default function () {
      console.log('foo');
    }
  • 相关阅读:
    2019年8月16日_实验室学术论文研讨
    2019年8月2日实验室学术研讨会议
    2019年7月26日实验室学术研讨会议
    2019年7月12日实验室开展学术研讨
    hdu 5547
    hdu 1286
    hdu 1272
    hdu 1213
    poj 2533 LIS(最长上升序列)
    HUD 5773 LIS(最长上升序列)
  • 原文地址:https://www.cnblogs.com/slightFly/p/14511485.html
Copyright © 2011-2022 走看看