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.

2
  • 1
    are you allowed to modify graphService? export const graph = { foo, bar }? Commented Apr 27, 2020 at 10:49
  • Thank you @user120242, that was exactly what I was looking for. If you post it as an answer I'll mark it as correct. Commented Apr 27, 2020 at 10:53

4 Answers 4

1

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

export const graph = { foo, bar }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

export const graph = {
    foo: () => { return 'foo' },
    bar: () => { return 'bar' }
};

Comments

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())

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.