0

I haven't found anything by searching on Google and I figured I could ask around here. I'm working with React, but I figure it should be similar in other JS/TS environments.

Say you have a module 'foo.ts':

export default function Foo(){
    function log1(){
        console.log("Hello world!");
    }
    function log2(){
        console.log("Goodbye, world!"); 
    }
}

As well as a module 'bar.ts':

export default function Bar(){
    function logNumbers(){
        for (var i: number = 0; i < 10; i++){
            console.log(i);
        }
    };
}

Which are both declared in an 'index.js' as such:

export Foo from './Foo';
export Bar from './Bar';

Then imported in my 'main.ts' file:

import * as mods from './modules'; //the folder in which foo.ts, bar.ts and index.js are located

function Main(){
    for (//every module imported){
        //find the functions 'log1', 'log2' and 'logNumbers'
        //do stuff with them.. i.e. run them in a particular order with cb
    }
}

Is such behavior even possible in JS/TypeScript?

I tried exporting the modules as an iterable array, like:

import Foo from './Foo'
import Bar from './Bar'

export default [
    Foo,
    Bar,
]

Then importing:

import * as mods from './modules';

function Main(){
    for (let i: number = 0; i < Object.entries(mods).length; i++){
        console.log(Object.values(mods)[i]);
    }
}

Of course, that just returns them as strings. I was hoping I could find something similar to the way you do it in Python.

Any ideas?

1 Answers1

0

yea should be able to. I think the best way is what you're doing with default export where you create an actual array in the module you're exporting and export that. You just have to import import mods from './modules'; instead of * as mods because its default export.

You can also export an object, or export individual functions from the module, but I dont know if thats a good idea. I would stick to collection all the function in the module you export (either as object or array whatever you want) and the export that either as default or const.

Here are some examples https://codesandbox.io/s/confident-wind-1ch89e?file=/src/index.ts

Max
  • 859
  • 5
  • 10