0

Suppose you have the following file:

graphService.js

const foo = () => { return 'foo' }

const bar = () => { return 'bar' }

How would it be possible to export all the functions so they can be used like this:

connsumer.js

import { graph } from 'src/services/graph/graphService'

graph.foo()
graph.bar()

With an extra file in between it's easy as you can do something like this:

graphMiddelFile.js

import * as graph from 'src/services/graph/graphCore'

export const graph = graph

Is this possible to do without a file in the middle and without using import * as graph from 'src/services/graph/graphService' in the consumer.js file?

I looked around the internet but couldn't find something similar. Thank you for your help.

DarkLite1
  • 13,637
  • 40
  • 117
  • 214

4 Answers4

1

If you are allowed to modify graphService, you can export an object.

export const graph = { foo, bar }
user120242
  • 14,918
  • 3
  • 38
  • 52
1

You can refer to: https://stackoverflow.com/a/33589850/10505608

As per this link:

Add in File 1

var Exported = {
   someFunction: function() { },
   anotherFunction: function() { },
}

module.exports = Exported;

To access it in File 2

var Export = require('path/to/Exported');
Export.someFunction();

I have also tried it, works smoothly.

Noopur Tiwari
  • 102
  • 1
  • 1
  • 7
0

You can try something like this, hope that i understood your question

export const graph = {
    foo: () => { return 'foo' },
    bar: () => { return 'bar' }
};
mdln97
  • 144
  • 1
  • 9
0

The functions foo and bar can be defined as properties of an object in which case only the object can be exported and then the functions can be accessed accordingly where they are needed.

export service = {
  foo : () => {return 'foo'},
  bar : () => {return 'bar' }
}

console.log("service", service.foo())
console.log("service", service.bar())
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Apr 28 '20 at 10:25