Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

How to import one function from various files in 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.

question from:https://stackoverflow.com/questions/65891796/how-to-import-one-function-from-various-files-in-same-folder-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...