博客
关于我
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/

你可能感兴趣的文章
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>