2

I need to use react-int outside a component and particularly inside an util file. In order to accomplish that i'am using this code https://gist.github.com/genadyp/435f4e264cb6e377836cf63bee8987d8 But i am facing an issue with eslint that fails and it does not accept using require inside a function and using a dynamic file path too.

here is eslint output:

error Unexpected require() global-require error Calls to require() should use string literals import/no-dynamic-require

Any advice and suggestions will be greatly appreciated.

//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);
  }
}
user2222
  • 444
  • 2
  • 8
  • 18

1 Answers1

2

You can read more about the reasoning for this rule here: https://eslint.org/docs/rules/global-require

If you are pretty sure about what you are doing you can disable the rule adding this comment before the statement: // eslint-disable-next-line global-require

Johnny Zabala
  • 2,285
  • 1
  • 12
  • 14
  • 1
    actually that's the point i am not sure that i am doing it right, otherwise i'll disable rules and it will work – user2222 Jul 14 '19 at 16:43
  • Ok. In my opinion it is not a good practice. I use `require` in the same way I use `import`, at the beginning of my file. If all you want to do is to read the file from the file system you can use fs module for that. For example you can use `__dirname` or `process.cwd()` with `path.join` and `fs.readFile`. – Johnny Zabala Jul 14 '19 at 17:24
  • fs is a node core module can't be used in react side – user2222 Jul 14 '19 at 20:24
  • Oh I see. Well in that case I would do something like this: https://codesandbox.io/embed/lucid-cohen-3ck90. Check the console and you'll se that `locales` is an object with `en` and `es` fields. Now the only think you'll need to do is to replace there `require` with `locales[locale.toLowerCase()]` – Johnny Zabala Jul 14 '19 at 21:38