Is the anti-pattern "require" inside componentWillMount?

Is the anti-pattern "require" inside componentWillMount? I am trying to dynamically load a locale based on the current region of the user.

componentWillMount(){ if (localStorage.getItem('locale') === 'da') { require('moment/locale/da') moment.locale('da') } } 

Thanks!

+5
source share
2 answers

Depending on which tool binds the code you use, the result may vary. If you use Webpack, it will allow you to “require” and “import” in place without missing class methods or anything else. This means that you are unlikely to benefit from this. The beam size will not be optimal, but you are likely to increase the likelihood of shooting in the leg.

However, there is a feature in Webpack 3 called lazy loading in Webpack that allows you to require a module at runtime. Webpack will take care of putting all the necessary JS code at runtime in the user's browser in order to require the module from the module and execute it (think about creating a "script" element and add it to the document ).

There is a note about lazy loading in the official Webpack documentation , which indicates a potential difference in the implementation of this function in different libraries. In this case, the code will look like

 async componentDidMount() { // <- note that componentWillMount isn't the best place to lazy-load a remote module, see @TryingToImprove comment const da = await import('moment/locale/da'); // <- Webpack will add its magic here moment.locale(da); } 

Also, read more about dynamic imports .

So, answering your question

Is the anti-pattern "require" inside componentWillMount?

I am afraid that this is still at the beginning of 2018, at least as you described, and if there will be no special attention to it.

On ESLint, there is actually a rule for this, global-require , which automatically generates a flag when the expression "import" or "require" is located anywhere other than the global scope.

+7
source

If you need modules at runtime, they will not be included at the time of picking, and it will be undefined.

0
source

Source: https://habr.com/ru/post/1275173/


All Articles