lau*_*kok 4 javascript node.js express ecmascript-6 koa2
如何在nodejs中对多个函数进行分组和导出?
我试图在 utils.js 中对我所有的 util 函数进行分组:
async function example1 () {
return 'example 1'
}
async function example2 () {
return 'example 2'
}
module.exports = { example1, example2 }
Run Code Online (Sandbox Code Playgroud)
然后在 home.js 中导入:
import { example1, example2 } from '../utils'
router.get('/', async(ctx, next) => {
console.log(example1()) // Promise { 'example 1' }
})
Run Code Online (Sandbox Code Playgroud)
我以为我会得到'example 1'
上面的测试用例?
有任何想法吗?
mar*_*pme 14
这将是我对您的出口问题的解决方案!并且不要es5 exports
与混合es6 imports
,这会变得非常奇怪 - 有时!
export const example1 = async () => {
return 'example 1'
}
export const example2 = async () => {
return 'example 2'
}
// other file
import { example1, example2 } from '../../example'
return example1()
Run Code Online (Sandbox Code Playgroud)
不过,如果您必须混合它们,请告诉我!我们也可以找到解决方案!
更多关于导出模块以及可能出现的问题!
MDN 导出和关于javascript 模块状态的简短故事
下面我分享的方式申报出口functions
以两种不同的方式。希望它有助于理解可以解决的不同方法。
"use strict";
// utils.js
const ex1 = function() {
console.log('ex1');
};
function ex2(context) {
console.log('ex2');
};
module.exports = { example1: ex1, example2: ex2 };
Run Code Online (Sandbox Code Playgroud)
您可以在另一个(外部)JS 文件(例如:app.js)中调用它们,如下所示:
// app.js
const utils = require('./utils');
utils.example1(); // logs 'ex1'
utils.example2(); // logs 'ex2'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30999 次 |
最近记录: |