首页 > 解决方案 > 在 forEach 循环中需要或导入

问题描述

我有以下对象:

   const basePoints = {}

我需要用 json 文件填充。目前我做:

   import WH11 from 'assets/WH11';
   const basePoints = { WH11}

我有十几个这样的 Json 文件,但在给定时间只能使用 2-3 个。而不是导入和加载我不需要的所有 JSON 文件,我想根据配置文件要求/导入,如下所示:

和我的 config.js:

  const config = {
        basePoints: {
              "WH11": "West Gate",
              "WH12": "West Gate Back Drop"
         }

       }

WH11、WH12 等基本上以 json 格式存在于我的资产目录中:

资产/基点/WH11.json

     {
       "startingID" : 198

      }

等等。现在可以有十几个或更多这样的 json 文件。用户只需在 config.js 中添加当月使用的那些。

有没有办法根据配置文件要求/导入 json 文件。如果我这样做,应用程序将无法编译:

     Object.keys(config.basePoints).forEach(key => {
          basePoints[key] = require('../assets/basepoints/' + key + '.json');

        });

错误是意外的 require()。

标签: javascript

解决方案


你可以使用最新的 ES2020 特性——动态导入

句法 -

import('/modules/<module_name>')
  .then(module => {
    //
  })
  .catch(err => {
    //
  });

您可以在此 MDN 文档中了解更多信息(向下滚动到动态导入部分) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import


推荐阅读