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.exports
和exports
什么区别?
The first exposes the object it points to. The latter exposes the properties of the object it points to.
第一个公开它指向的对象。 后者公开了它指向的对象的属性 。
node 实现文件导出