javascript - 在 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()。
解决方案
你可以使用最新的 ES2020 特性——动态导入
句法 -
import('/modules/<module_name>')
.then(module => {
//
})
.catch(err => {
//
});
您可以在此 MDN 文档中了解更多信息(向下滚动到动态导入部分) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
推荐阅读
- web-scraping - Fail Scrapy - 它提供一个空的输出
- ssl - nginx https 不工作
- javascript - 我想在 flexbox 中更改我的板块在 CSS 中的位置
- bash - 根据输出高亮 grep 结果以不同的颜色
- php - 实时服务器上的 VerifyCsrfToken.php 中的 TokenMismatchException
- ios - 适用于所有 iOS 设备的背景图像大小指南
- azure - Azure 数据工厂:URI 无效:Uri 方案太长
- php - PayPal:出现错误:“访问 https://api.sandbox.paypal.com/v1/payments/payment 时出现 Http 响应代码 400。”
- ios - 使用应用内购买或第三方支付网关
- javascript - 使用 Javascript 的 Chrome 扩展