Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - how group and export multiple functions in a separate file?

How can I group and export multiple functions in nodejs?

I am trying to group all my util functions in utils.js:

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

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

module.exports = { example1, example2 }

And then be imported in home.js:

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

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

  })

I thought I would get 'example 1' for the test case above?

Any ideas?

like image 519
Run Avatar asked Aug 20 '17 10:08

Run


People also ask

How do I export multiple functions from a single js file?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.

Can you have multiple exports in one file?

You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax. After the export keyword, you can use let , const , and var declarations, as well as function or class declarations.

How do I export multiple functions from one file React?

Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.


2 Answers

This would be my solution for your exporting problem! And don't mix es5 exports with es6 imports, that can get very weird - sometimes!

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

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


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

Nevertheless if you have to mix them, just let me know! We can find a solution for this aswell!


More about exporting modules and what can go wrong!

MDN Exports and the a short story about the state of javascript modules

like image 156
marpme Avatar answered Nov 15 '22 08:11

marpme


Below I have shared a way to declare the exporting functions in 2 different ways. Hope it helps understand the different ways in which it could be solved.

"use strict";
// utils.js

const ex1 = function() {
  console.log('ex1');
};

function ex2(context) {
  console.log('ex2');
};

module.exports = { example1: ex1, example2: ex2 };

You could invoke them in another (external) JS file (ex: app.js) as follows:

// app.js
const utils = require('./utils');

utils.example1(); // logs 'ex1'
utils.example2(); // logs 'ex2'
like image 23
Hamzeen Hameem Avatar answered Nov 15 '22 07:11

Hamzeen Hameem