【问题标题】:How to fix eslint failure when requiring a file with dynamic path inside a function?在函数内需要具有动态路径的文件时如何修复 eslint 失败?
【发布时间】:2019-11-23 12:11:39
【问题描述】:

我需要在组件外部使用 react-int,尤其是在 util 文件内部。为了实现这一点,我正在使用此代码https://gist.github.com/genadyp/435f4e264cb6e377836cf63bee8987d8 但是我遇到了一个失败的 eslint 问题,它不接受在函数内部使用 require 并且也使用动态文件路径。

这里是 eslint 输出:

error Unexpected require() global-require 错误调用 require() 应该使用字符串字面量 import/no-dynamic-require

任何意见和建议将不胜感激。

//util.js
export function formatMessage(t, locale) {
    if (t=== 0 || t === 2400) {
        const translations 
        =require(`src/locales/${locale.toLowerCase()}.json`));

        const intlProvider = new IntlProvider({ locale, messages: 
        translations }, {});
        const mes = defineMessages({
            morning: {
                id: 'greeting.morning',
                defaultMessage: 'hello',
            },
            evening: {
                id: 'greeting.evening',
                defaultMessage: 'good evening',
            },
       });
       const { intl } = intlProvider.getChildContext();

       return t === 0 ? intl.formatMessage(mes.morning) : 
           intl.formatMessage(mes.evening);
  }
}

【问题讨论】:

    标签: reactjs react-redux internationalization eslint react-intl


    【解决方案1】:

    您可以在此处阅读更多关于此规则的原因:https://eslint.org/docs/rules/global-require

    如果您非常确定自己在做什么,您可以禁用在语句前添加此评论的规则:// eslint-disable-next-line global-require

    【讨论】:

    • 实际上这就是我不确定我做对了的关键,否则我会禁用规则并且它会起作用
    • 好的。在我看来,这不是一个好习惯。我使用require 的方式与在文件开头使用import 的方式相同。如果您只想从文件系统中读取文件,则可以使用 fs 模块。例如,您可以将__dirnameprocess.cwd()path.joinfs.readFile 一起使用。
    • fs 是 node 核心模块,不能在 react 端使用
    • 哦,我明白了。那么在这种情况下,我会做这样的事情:codesandbox.io/embed/lucid-cohen-3ck90。检查控制台,您会发现locales 是一个具有enes 字段的对象。现在你唯一需要做的就是用locales[locale.toLowerCase()]替换require
    猜你喜欢
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2020-08-20
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多