Home > Blockchain >  How to export multiple functions Javacript?
How to export multiple functions Javacript?

Time:12-16

I want to export default all functions inside export default, but every time I try to import them in another file, I get the error that the functions don't exists. Am I importing wrong?

export default () => {

  // methods
  const makeRequest = async () => {

    async function useAllBenefits() {
      ...
    return payload;
    }

    async function useTopBenefits() {
     ...
    return payload;

    }

    // exposed
    return {
      useAllBenefits,
      useTopBenefits,
      makeRequest
    };
  };
}

myotherfile.js

import all from '../myFile'

console.log(all.useAllBenefits)

CodePudding user response:

  1. Don't put them inside another function
  2. Use the export keyword

Such:

export const aFunction = () => {};
export const anOtherFunction = () => {};
const someDefaultExport = () => {};
export default someDefaultExport;

Then you can import them:

import theDefault, { aFunction, anOtherFunction } from "../myFile";

CodePudding user response:

If you want to export multiple functions AS DEFAULT you can do it by exporting one object whose properties are functions.

export default {
   function1: () => {},
   function2: () => {},
   function3: () => {}
}

Now in another file you can import them and use as bellow:

import all from '../myFile.js';
all.function1();
all.function2();

CodePudding user response:

Method 1. export each functions

myFunction.js

export const sum = (a,b) {
   return a   b;
}

export const multiply = (a,b) {
   return a * b;
} 

Method 2.

myFunction.js

const sum = (a,b) {
   return a   b;
}

 const multiply = (a,b) {
   return a * b;
} 

export default {sum, multiply}

Import section

file.js

import all from './myFunction.js'

all.sum(10, 11);

Or file.js

import {sum, multiply} from './myFunction.js'

sum(10, 11);
  • Related