-1

I have one file containing many functions. Similar to below,

export const func1 = () => {
}

export const func2 = () => {
}

export const func3 = () => {
}

export const func4 = () => {
}

Now I want to use all this function in another file.

Method 1 is import {func1, func2, func3, func4} from 'path'.
Method 2 (which I don't want to use) is import * as access from 'path'

Method 1 approach is what I am using right now. But when func file gets bigger, this will not be readable. So, how to use the functions without creating aliases and simply func1() and not access.func1() ?

Tirath Sojitra
  • 359
  • 4
  • 15
  • Method 1 is how you do it. If you have that many functions in a module that are so unrelated that it doesn't make sense to wrap them under a name, maybe they shouldn't be in the same module? – Heretic Monkey Jan 26 '22 at 16:52

2 Answers2

1

You should really make up your mind between the two as they are the most readable and clean solutions.

First option can be made more readable with:

import {
  func1,
  func2,
  func3,
  func4
} from 'path';

Nevertheless, if you really want an alternative syntax without having to list the exports, it is technically possible to load all the exported properties into the global object through:

Object.assign(globalThis, require('path'))

However, I would highly advise against this as it'll make your code very difficult to maintain. Global variables are painful enough, but unknown global variables coming from another file will be a nightmare. Use at your own risk.

skara9
  • 4,042
  • 1
  • 6
  • 21
1

You can import with your Method 2 and then can use object destructuring on the access object like this and use them directly.

import * as access from 'path';

const {func1, func2, func3, func4} = access;

func1();
Dharman
  • 30,962
  • 25
  • 85
  • 135
Shreenath
  • 51
  • 5
  • 1
    How is this any better than `import {func1,func2,func2,func4} from 'path';`? You still have two write something out for every "`funcN`". This just splits it into two steps rather than one. – Heretic Monkey Jan 26 '22 at 17:16
  • The question wants to keep imports readable when there is more number of functions to be imported and still use those functions without using the `importObj.functionName` notation. So, in that spirit, I think it solves the problem faced by the OP, but for which is better, I am not aware of any tangible advantages of either approach other than personal preference. – Shreenath Jan 26 '22 at 18:18