javascript - Nodejs - 如何在单独的文件中分组和导出多个函数?

标签 javascript node.js express ecmascript-6 koa2

如何在 nodejs 中分组和导出多个函数?

我正在尝试将我所有的 util 函数分组到 utils.js 中:

async function example1 () {
    return 'example 1'
}

async function example2 () {
    return 'example 2'
}

module.exports = { example1, example2 }

然后在home.js中导入:

  import { example1, example2 } from '../utils'

  router.get('/', async(ctx, next) => {
    console.log(example1()) // Promise { 'example 1' }

  })

我以为我会得到上面测试用例的'example 1'

有什么想法吗?

最佳答案

这将是我解决您的导出问题的方法!并且不要将 es5 exportses6 imports 混合使用,这有时会变得很奇怪!

export const example1 = async () => {
   return 'example 1'
}

export const example2 = async () => {
   return 'example 2'
}


// other file
import { example1, example2 } from '../../example'
return example1()

不过,如果您必须混合使用它们,请告诉我!我们也可以找到解决方案!


更多关于导出模块和可能出错的地方!

MDN Exports还有一个关于the state of javascript modules的小故事

关于javascript - Nodejs - 如何在单独的文件中分组和导出多个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45781063/

相关文章:

javascript - 将 Angular 4 应用程序静态 Assets 转发到/PORT 路径而不是主域

node.js - 在 IBM Cloud Foundry 中运行 nodejs 应用程序时文件不压缩

node.js - 在 Angular 2 中创建构建时 JavaScript 堆内存不足错误

json - node-redis 错误 : Deprecated: The SET command contains a argument of type Object

javascript - 如何解构有时被接收为 null 的对象属性

javascript - 在 Node 中形成元素数组键并表示

javascript - 如何在jquery语法函数中发送参数?

javascript - 在添加新标记之前如何从谷歌地图中删除所有标记

javascript - jQuery fullPage : All images loading at same time

javascript - 如何使用按钮编辑或输入焦点InputElement