使打字稿知道 webpack 的 `require.context` 中的所有键 [英] make typescript know all keys from `require.context` of webpack

查看:28
本文介绍了使打字稿知道 webpack 的 `require.context` 中的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个相对的问题是https://stackoverflow.com/a/53015011/2326199

@jcalz 的答案在所有键都经过硬编码时效果很好.但我想知道是否有可能没有像使用 webpack 的 require.context 这样的硬代码.

The answer by @jcalz works great when all keys are hard coded. But I wonder if it's possible without hard code like using require.context of webpack.

这里的 repo 演示了我想要的:

Here's repo demonstrate what I want:

  • components/icon.tsx
  • 需要所有 svg 图标
  • 所有 svg 名称都从 components/icon.tsx
  • 导出为 ICONS
  • index.tsx 处输入 ICONS. 时,我应该能够收到自动完成提示,对于这个 repo,它应该给 BluetoothonClose
  • all svg icons are required at components/icon.tsx
  • all svg name are exported as ICONS from components/icon.tsx
  • I should able to receive auto-complete hint when typing ICONS. at index.tsx, for this repo, it should give Bluetoothon and Close

推荐答案

你可以试试这个.../locales 目录下有很多 json 文件.根据用户的选择从特定区域加载所有消息.

function loadLocaleMessages() {
  const locales = require.context(
    "./locales",
    true,
    /[A-Za-z0-9-_,\s]+\.json$/i
  );

  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

这篇关于使打字稿知道 webpack 的 `require.context` 中的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆