Tip of the day:
If you are wondering how to stop requiring the same resources multiple times, then the good news is that require handles this pretty well.
Let’s take an example to understand, why this question arises.
export const formatDate = (date) => {
let moment = require('moment')
require('moment/locale/da')
const momentdate = moment(date)
return momentdate.format('ddd Do MMM')
}
In the following code example, we are trying to avoid importing Momentjs on every page but only when formatDate method is called.
Now there was a doubt, what if formatDate is called inside the loop, will Momentjs will be required the number of times the loop runs?
The answer is “No”, but why & how?
require
is always “require once”. After you call require
the first time, require
uses a cache and will always return the same object.
Any executable code floating around in the module will only be run once.
On the other hand, if you do want it to run initialization code multiple times, simply throw that code into an exported method, followed by the detailed reply given on StackOverflow
And if you have trouble understanding the difference between import and require, you must read this well-explained article JavaScript require vs import.