javascript

JS: require a JS file only once in Node.js?

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.

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk