天天看点

exports和module.exports的区别exports导出的是一个实例对象。module.exports导出的是对象本身

exports导出的是一个实例对象。

要调用导出的方法或者属性时,要用当前实例对象去调用。如下述代码中,导出的是builds对象,使用getAllBuilds方法时要调用此方法。

exports.js 

const builds = {
  // Runtime only (CommonJS). Used by bundlers e.g. Webpack & Browserify
  'web-runtime-cjs-dev': {
    entry: 'web/entry-runtime.js',
  },
  'web-runtime-cjs-prod': {
    entry: 'web/entry-runtime.js',
  },
  // Runtime+compiler CommonJS build (CommonJS)
  'web-full-cjs-dev': {
    entry:'web/entry-runtime-with-compiler.js',
  }
}


exports.getAllBuilds = () => Object.keys(builds);
           

test.js 

let builds = require('./export');

console.log(builds);
console.log("-------------------");
console.log(builds.getAllBuilds);
console.log("-------------------");
console.log(builds.getAllBuilds());
           

执行结果:

exports和module.exports的区别exports导出的是一个实例对象。module.exports导出的是对象本身

module.exports导出的是对象本身

如下述代码中,导出的就是一个Function,可以直接执行

exports.js 

const builds = {
  // Runtime only (CommonJS). Used by bundlers e.g. Webpack & Browserify
  'web-runtime-cjs-dev': {
    entry: 'web/entry-runtime.js',
  },
  'web-runtime-cjs-prod': {
    entry: 'web/entry-runtime.js',
  },
  // Runtime+compiler CommonJS build (CommonJS)
  'web-full-cjs-dev': {
    entry:'web/entry-runtime-with-compiler.js',
  }
}

module.exports = () => Object.keys(builds);

// exports.getAllBuilds = () => Object.keys(builds);
           

test.js 

let builds = require('./export');

console.log(builds);
console.log("-------------------");
console.log(builds());
           

执行结果:

exports和module.exports的区别exports导出的是一个实例对象。module.exports导出的是对象本身

说明:

exports和module.exports不要同时使用,否则,module.exports会覆盖exports.即exports失效。