Search code examples
javascriptimportexport

How to import one function from various files in the same folder in Javascript?


I have multiple functions distributed in seven javascript files in the same folder. I want to import them to another file without necessarily exporting one by one. For the sake of simplicity, suppose that I have just one function in each file and then I'm gonna use default export. So .forEach file in "scripts", I could do:

export default myFunc1 // first.js
export default myFunc2 // second.js
export default myFunc3 // third.js
...

And then, inside the file I want to import:

import myFunc1 from "./scripts/first.js"
import myFunc2 from "./scripts/second.js"
import myFunc3 from "./scripts/third.js"
...

However I want to know if there's a simpler way to perform this, since variations like "export * from /scripts" seems to not work in this case.


Solution

  • You could add an index.js file in the same directory as all the Javascript files that you want to import. Then, import all the functions into this one index.js file. This way, you won't have to list out each and every one of the functions (or their files) everywhere you use them.

    export default myFunc1 // first.js
    export default myFunc2 // second.js
    export default myFunc3 // third.js
    ...
    

    index.js file would be

    import myFunc1 from "./scripts/first.js"
    import myFunc2 from "./scripts/second.js"
    import myFunc3 from "./scripts/third.js"
    ...
    export {
    myFunc1,
    myFunc2,
    myFunc3,
    ...
    };
    

    Suppose these function files and the index.js file are located in a directory named functions, and you want to access them from a file that is one level higher you would do:

    import "./functions"; // Or "functions"
    

    Now, keep in mind that this solution is only desirable if you are using these functions in more than one place. If you are not, you can use your original method.