node 实现文件导出_使用导出从Node文件公开功能

node 实现文件导出

Node has a built-in module system.

Node具有内置的模块系统。

A Node.js file can import functionality exposed by other Node.js files.

Node.js文件可以导入其他Node.js文件公开的功能。

When you want to import something you use

当您想导入某些东西时

const library = require('./library')

to import the functionality exposed in the library.js file that resides in the current file folder.

导入位于当前文件夹中的library.js文件中公开的功能。

In this file, functionality must be exposed before it can be imported by other files.

在此文件中,必须先公开功能,然后才能由其他文件导入。

Any other object or variable defined in the file by default is private and not exposed to the outer world.

默认情况下,文件中定义的任何其他对象或变量都是私有的,不会暴露给外界。

This is what the module.exports API offered by the module system allows us to do.

这就是module系统提供的module.exports API允许我们执行的操作。

When you assign an object or a function as a new exports property, that is the thing that’s being exposed, and as such, it can be imported in other parts of your app, or in other apps as well.

当您将对象或函数分配为新的exports属性时,这就是要公开的内容,因此,可以将其导入应用程序的其他部分或其他应用程序中。

You can do so in 2 ways.

您可以通过两种方式进行操作。

The first is to assign an object to module.exports, which is an object provided out of the box by the module system, and this will make your file export just that object:

首先是将一个对象分配给module.exports ,这是模块系统提供的开箱即用的对象,这将使文件导出该对象

const car = {
  brand: 'Ford',
  model: 'Fiesta'
}

module.exports = car

//..in the other file

const car = require('./car')

The second way is to add the exported object as a property of exports. This way allows you to export multiple objects, functions or data:

第二种方法是将导出的对象添加为一个属性exports 。 通过这种方式,您可以导出多个对象,函数或数据:

const car = {
  brand: 'Ford',
  model: 'Fiesta'
}

exports.car = car

or directly

或直接

exports.car = {
  brand: 'Ford',
  model: 'Fiesta'
}

And in the other file, you’ll use it by referencing a property of your import:

在另一个文件中,您将通过引用导入的属性来使用它:

const items = require('./items')
items.car

or

要么

const car = require('./items').car

What’s the difference between module.exports and exports?

module.exportsexports什么区别?

The first exposes the object it points to. The latter exposes the properties of the object it points to.

第一个公开它指向的对象。 后者公开它指向的对象的属性

翻译自: https://flaviocopes.com/node-export-module/

node 实现文件导出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值