2017-08-20 2 views
0

nodejで複数の関数をグループ化してエクスポートするにはどうすればよいですか?私はutils.jsにグループにすべての私のutilの機能をしようとしていますNodejs - 複数の機能をグループ化して別々のファイルにエクスポートする方法は?

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'になるだろうと思いました上記のケース?

アイデア?

+0

愚かな質問についてのショートストーリー:あなたは、関数を呼び出すことを忘れたのか? 'console.log(example1()を待っている);'? –

+1

'example1'を非同期関数(不明)な理由としてマークしたため、' example 1'の代わりに 'Promise {'example 1'}'を取得しています。解決された価値を得るには、次のようにします: 'await example1()'。回答に感謝します。 – alexmac

答えて

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 Exportsthe state of javascript modules

+0

'es5 exports'はどうですか? 'es6 exports'とみなされるもの – laukok

+1

ES5 exportは' module.defaults = {example1、example2} 'のような古い構文です。新しい(ES6)の1つは 'export default {example1、example2}' – Kyon

+0

です。この 'export {example1、example2 }'はどうでしょうか?それもes5ですか? – laukok

関連する問題