【问题标题】:Require , how to do a fallback when module does not exist要求,当模块不存在时如何做一个回退
【发布时间】:2018-06-12 10:02:09
【问题描述】:

我有一个应用程序,我需要一个可能可用也可能不可用的文件。如果该文件不可用,我需要检查另一个文件。第三个选项将是默认的。到目前为止我有这个

const file = require('./locales/${test1}') || require('./locales/${test2}') || require('./locales/default')

但它给了我一个错误,说找不到模块。我该如何做到最好?

我确实尝试了https://www.npmjs.com/package/node-require-fallback,但尽管我的节点版本还可以,但它似乎不起作用

const messages = require('./locales/${test1}') 效果很好,但是

const messages = requireIfExists('./locales/${test1}', './locales/${test2}') 失败

【问题讨论】:

  • 您是否在模板字符串中使用 ` 字符而不是单引号?模块is on github 的源代码非常简单,所以我预计您使用requireIfExists 的方式有问题

标签: javascript require


【解决方案1】:

在普通节点应用程序中,您可以使用 try-catch 块:

var module;

try {
  module = require(`./locales/${test1}`);

  } catch(error) {
    // Do something as a fallback. For example:

    module = require('./locales/default');
  }
}

【讨论】:

    【解决方案2】:

    使用 try/except,您可以自己实现一个复制requireIfExists 的函数。

    function requireIfExists(...modules) {
      for (let module of modules) {
        try {
          return require(module);
        } catch (error) {
          // pass and try next file
        }
      }
      throw('None of the provided modules exist.')
    }
    

    此外,请确保在使用模板字符串时使用 ` 字符而不是引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 2020-12-25
      相关资源
      最近更新 更多