组织大量导入的JavaScript功能
我正在创建一个具有许多互动练习的教育网站。每个练习都有一个生成每个问题/答案组合的功能。目前,我正在从文件中导入所有这些:
import * as exerciseHelpers from "../helpers/exercise_helpers.js";
在辅助文件中,每个练习都具有其功能:
export function exercise1() {
//stuff for exercise 1
}
export function exercise2() {
//stuff for exercise 2
}
我担心该文件会很难通过100次练习来维护。另外,我真的不想加载所有功能,只是为了调用与当前练习有关的功能。
当我运行练习时,我会称呼:
exerciseHelpers[thisExerciseFunction]();
理想情况下,我想在自己的文件练习中创建每个函数1.js/corycorce2.js等,然后才导入我需要的一个。
但是看来我无法基于变量导入功能。
有没有更好的方法来组织此功能,以便每个功能都可以在需要时加载的单独文件中?
I'm creating an educational website with a lot of interactive exercises. Each exercise has a function which generates each question/answer combination. At the moment I am importing all of these from a file:
import * as exerciseHelpers from "../helpers/exercise_helpers.js";
Inside the helper file each exercise has its function:
export function exercise1() {
//stuff for exercise 1
}
export function exercise2() {
//stuff for exercise 2
}
I am worried this file will get very hard to maintain with 100s of exercises. Also I don't really want to load in all the functions just to call the one relating to the current exercise.
When I'm running the exercise I call:
exerciseHelpers[thisExerciseFunction]();
Ideally I'd like to create each function in its own file exercise1.js/exercise2.js etc, and then just import the one I need.
But it seems I can't import functions based on a variable.
Is there a better way to organise this so each of these functions can be in a separate file that is loaded in when needed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的
helpers
目录中创建index.js
文件。内部index.js
从其各自的文件中导出您的所有功能,例如:您可以在自己的文件中具有所有实用程序功能,但仍会从
index.js.js
中导入所有功能:或者,您可以用命名导入导入所需的一个:
Create an
index.js
file in yourhelpers
directory. Insideindex.js
export all your functions from their respective files, like:Then you can have all your utility functions in their own files but still import everything from
index.js
:Or you can import the one you need with named import: