Nodejs - 如何在单独的文件中分组和导出多个函数?
Nodejs - how group and export multiple functions in a separate file?
如何在 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 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()
不过,如果你必须混合使用它们,请告诉我!我们也可以找到解决方案!
更多关于导出模块和可能出错的信息!
MDN Exports and the a short story about the state of javascript modules
下面我分享了一种以 2 种不同方式 声明导出 functions
的方法。希望它有助于理解解决问题的不同方法。
"use strict";
// utils.js
const ex1 = function() {
console.log('ex1');
};
function ex2(context) {
console.log('ex2');
};
module.exports = { example1: ex1, example2: ex2 };
您可以在另一个(外部)JS 文件(例如:app.js)中调用它们,如下所示:
// app.js
const utils = require('./utils');
utils.example1(); // logs 'ex1'
utils.example2(); // logs 'ex2'
async function example1 () {
return 'example 1'
}
async function example2 () {
return 'example 2'
}
module.exports.example1 = example1;
module.exports.example2 = example2;
像这样在 home.js 中导入:
const fun = require('./utils');
fun.example1();
如何在 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 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()
不过,如果你必须混合使用它们,请告诉我!我们也可以找到解决方案!
更多关于导出模块和可能出错的信息!
MDN Exports and the a short story about the state of javascript modules
下面我分享了一种以 2 种不同方式 声明导出 functions
的方法。希望它有助于理解解决问题的不同方法。
"use strict";
// utils.js
const ex1 = function() {
console.log('ex1');
};
function ex2(context) {
console.log('ex2');
};
module.exports = { example1: ex1, example2: ex2 };
您可以在另一个(外部)JS 文件(例如:app.js)中调用它们,如下所示:
// app.js
const utils = require('./utils');
utils.example1(); // logs 'ex1'
utils.example2(); // logs 'ex2'
async function example1 () {
return 'example 1'
}
async function example2 () {
return 'example 2'
}
module.exports.example1 = example1;
module.exports.example2 = example2;
像这样在 home.js 中导入:
const fun = require('./utils');
fun.example1();