亲宝软件园·资讯

展开

Node.js   exports

Chrislinlin 人气:0

介绍

示例

test.js

console.log('module', module)
console.log('module.exports', module.exports)
console.log('exports', exports)
console.log('module.exports === exports', module.exports === exports)

控制台执行 node test.js打印日志如下:

module Module {
  id: '.',
  path: 'E:\lin\webpack-learning\src\cjs\demo1',
  exports: {},
  filename: 'E:\lin\webpack-learning\src\cjs\demo1\test.js',
  loaded: false,
  children: [],
  paths: [
    'E:\lin\webpack-learning\src\cjs\demo1\node_modules',
    'E:\lin\webpack-learning\src\cjs\node_modules',
    'E:\lin\webpack-learning\src\node_modules',
    'E:\lin\webpack-learning\node_modules',
    'E:\lin\node_modules',
    'E:\node_modules'
  ]
}
module.exports {}
exports {}
module.exports === exports true

从源码中理解

github.com/nodejs/node…

const exports = this.exports;
const thisValue = exports;
const module = this;

说明:exports 是 module.exports 的引用

通过示例理解

示例一

test1.js

exports.name = 'lin';
module.exports.age = 18;

console.log('module.exports', module.exports)
console.log('exports', exports)
console.log('module.exports === exports', module.exports === exports)

index.js

const test = require('./test1')
console.log("test", test);

控制台执行 node index.js,打印日志如下:

module.exports { name: 'lin', age: 18 }
exports { name: 'lin', age: 18 }
module.exports === exports true 
test { name: 'lin', age: 18 }

画图说明:

示例二

test2.js

module.exports.name = 'lin'
exports = {
  name: 'myName',
  age: 6
}
console.log('module.exports', module.exports)
console.log('exports', exports)
console.log('module.exports === exports', module.exports === exports)

index.js 改为引入 test2.js 模块

const test = require('./test2')
console.log("test", test);

控制台执行 node index.js打印日志如下:

module.exports { name: 'lin' }
exports { name: 'myName', age: 6 }
module.exports === exports false
test { name: 'lin' }

画图说明:

示例三

test3.js

module.exports = {
  name: 'lin',
  age: 18
}

exports.name = "myName"
console.log('module.exports', module.exports)
console.log('exports', exports)
console.log('module.exports === exports', module.exports === exports)

index.js 改为引入 test3.js 模块

const test = require('./test3')
console.log("test", test);

控制台执行 node index.js打印日志如下:

module.exports { name: 'lin', age: 18 }
exports { name: 'myName' }
module.exports === exports false
test { name: 'lin', age: 18 }  

画图说明:

示例四

test4.js

exports = {
  name: 'lin',
  age: 18
}
module.exports = exports
module.exports.job = 'FE'
console.log('module.exports', module.exports)
console.log('exports', exports)
console.log('module.exports === exports', module.exports === exports)

index.js 改为引入 test4.js 模块

const test = require('./test4')
console.log("test", test);

控制台执行 node index.js打印日志如下:

module.exports { name: 'lin', age: 18, job: 'FE' }
exports { name: 'lin', age: 18, job: 'FE' }
module.exports === exports true
test { name: 'lin', age: 18, job: 'FE' }

画图说明:

小结

加载全部内容

相关教程
猜你喜欢
用户评论