组织大量导入的JavaScript功能

发布于 2025-02-10 12:00:30 字数 609 浏览 0 评论 0原文

我正在创建一个具有许多互动练习的教育网站。每个练习都有一个生成每个问题/答案组合的功能。目前,我正在从文件中导入所有这些:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聊慰 2025-02-17 12:00:30

在您的helpers目录中创建index.js文件。内部index.js从其各自的文件中导出您的所有功能,例如:

export * from './exercise1.js';
export * from './exercise2.js';

您可以在自己的文件中具有所有实用程序功能,但仍会从index.js.js中导入所有功能:

import * as exerciseHelpers from '../helpers';

或者,您可以用命名导入导入所需的一个:

import { exercise1 } from '../helpers';

Create an index.js file in your helpers directory. Inside index.js export all your functions from their respective files, like:

export * from './exercise1.js';
export * from './exercise2.js';

Then you can have all your utility functions in their own files but still import everything from index.js:

import * as exerciseHelpers from '../helpers';

Or you can import the one you need with named import:

import { exercise1 } from '../helpers';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文