博客
关于我
node.js 导出模块的两种方式 exports module.exports
阅读量:254 次
发布时间:2019-03-01

本文共 885 字,大约阅读时间需要 2 分钟。

在模块化编程中,模块的导出方式有两种主要方法,分别是exportsmodule.exports。了解这两种方法的区别及其适用场景,对于理解模块导出机制具有重要意义。

exports与module.exports的关系

在初始阶段,exportsmodule.exports实际上是指向同一块内存区域,内容都是一个空对象。具体来说:

exports === module.exports // 输出是 true

这意味着在定义模块时,无论直接使用exports还是module.exports赋值,结果都是一样的。例如:

//1 mymodule.jsexports.f = function() {}exports.pi = 3.1415926//2 mymodule.jsmodule.exports.f = function() {}module.exports.pi = 3.1415926

两种写法的效果完全一致。

exports的特殊情况

需要注意的是,当直接将exports对象赋值时(例如:exports={a:1,b:2}),此时exports就不再指向module.exports,而是指向一个新对象。这种情况下,exportsmodule.exports就不再是同一个对象。

如何正确导出模块

在引入某模块时,应以该模块代码中module.exports指向的内容为准。例如:

// mymodule.jsmodule.exports = {  myPI: 3.14,  add: (a, b) => a + b}

这种方式是最常见且推荐的导出方式。

常见模块的导出方式

在实际开发中,许多模块采用不同的导出方式。例如:

  • cookie模块通常使用module.exports的形式导出。
  • body-parser模块同样采用module.exports的方式。
  • array-flatten模块也遵循这一规则。

结论

在导出模块时,建议只使用一种方式,并且建议直接使用module.exports。这不仅简化了代码,也符合大多数模块的标准导出方式。

转载地址:http://ddca.baihongyu.com/

你可能感兴趣的文章
NotImplementedError: Could not run torchvision::nms
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>