我是 Node js 的新手,在浏览一些博客和教程时,我遇到了一种不同的导入模块的方法
对于某些人使用:
const {app} = require('./routes/index');
Run Code Online (Sandbox Code Playgroud)
很少有网站关注:
const app= require('./routes/index');
Run Code Online (Sandbox Code Playgroud)
那么第一和第二之间有什么区别,我真的很困惑,并且没有得到任何正确的解释
小智 5
const app = require('./routes/index');
Run Code Online (Sandbox Code Playgroud)
从该文件导入默认值或所有内容
const { app, app2 } = require('./routes/index');
Run Code Online (Sandbox Code Playgroud)
从该文件导入特定对象。
有两种方法可以从 ./routes/index.js 导入内容。
第一个是,
const app = () => {
console.log("Sample function")
}
// MOST IMPORTANT!
export default app
// Here, we are exporting app from that file as default. We use this normally, when we export only one thing from a file, and in this case, you can use,
Run Code Online (Sandbox Code Playgroud)
const app = require('./routes/index')
Run Code Online (Sandbox Code Playgroud)
因为只有一个对象被导出,所以你可以使用它,但是!
const app = () => {
console.log("Sample Function 1")
}
const app2 = () => {
console.log("Sample Function 2")
}
export { app, app2 }
// Here, we are exporting two different objects/functions NOT as default. As there are two different object, you need to specify which one to import
Run Code Online (Sandbox Code Playgroud)
现在,要导入这些函数之一,我们可以使用,
const { app2 } = require('./routes/index');
// OR
const { app } = require('./routes/index');
// OR
const { app, app2 } = require('./routes/index');
Run Code Online (Sandbox Code Playgroud)
如果您想同时导入两者,您也可以使用,
const app = require('./routes/index')
// The first function can be accessed/called by,
app.app()
// or
app.app2()
Run Code Online (Sandbox Code Playgroud)
但是,由于这会使其更加混乱并占用更多内存,因此我们通常不会一次全部导入。
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |