javascript - 动态导入本地和远程文件
问题描述
背景
我目前正在构建一个具有相当奇怪的本地化基础架构的渐进式 Web 应用程序 (PWA)。它有两个要素:
- 本地定义的翻译(在项目 repo 中定义)
- 远程定义的翻译(静态存储在 CDN 中)
从理论上讲,这需要工作的方式非常简单:
- 检测语言环境
- 导入区域设置的本地翻译
- 导入语言环境的远程翻译
- 组合对象
- 将它们提供给应用程序
问题
这引发了一些问题;
- 如何仅动态导入必要的“本地”翻译?
- 如果模块/文件名是动态的,webpack 如何知道捆绑本地翻译?
- 如何仅动态导入必要的“远程”翻译?
我试过的
我目前有以下文件结构:
/i18n
│ index.js
│
└───/translations
│ │
│ └───/en
│ │ │ index.js
│ │ │ meta.json
│ │ │ ...
│ │
│ └───/es
│ │ │ index.js
│ │ │ meta.json
│ │ │ ...
我的意图如下:
/i18n/index.js
- 执行必要翻译的初始设置和动态加载/i18n/translations/XX/index.js
- 收集并导出目录中的所有翻译json
文件XX
我还没有设法做到这一点,因为我不完全确定如何最好地实现它,但这就是我到目前为止所拥有的:
/i18n/index.js
- 设置本地化
// Determine the locale...
const locale = 'XX' // For example purposes
const translations = {};
// Import the local translations
// IS THIS THE RIGHT WAY TO DO THIS?
translations.local = require(`./translations/${locale}/index.js`);
// Import the remote translations here...
// Maybe use importScripts() but I am fairly certain this is
// only available in the service worker...
// HOW CAN THIS BE DONE?
translations.remote = '';
translations.combined = Object.assign(translations.local, translations.remote);
/i18n/translations/XX/index.js
- 本地进口
export default {
meta: require('./meta')
// etc...
}
我的问题
如问题部分所述,我不完全确定如何实现我所需要的。谁能建议如何最好地实现这一点?
如果我目前拥有的不是好的做法,请随意建议替代文件结构......
解决方案
推荐阅读
- ios - 应用程序崩溃并调用 [ServicesDaemonManager] interruptHandler。-[FontServicesDaemonManager 连接]_block_invoke
- javascript - 如何使用 Selenium 和 Python 从由空格分隔的文本节点获取文本
- fonts - 无法嵌入字体时的位图文本
- javascript - .map() 显示来自 api 的数据的问题
- sql - 获取 oracle db 中的所有视图以及行数、列数、主键等详细信息
- reactjs - 在 ReactJs 中执行函数时禁用按钮
- mysql - 对于一个表中的所有条目,添加到另一个表
- eclipse - Eclipse IDE 中奇怪的选项卡名称字符
- powershell - 在 Powershell 中复制文件时需要帮助
- angular - 尝试将自定义 svg 添加到角度材质图标注册表