sindresorhus / clear-module

Clear a module from the cache
MIT License
182 stars 25 forks source link

Clear single module #11

Closed Dejmek closed 4 years ago

Dejmek commented 5 years ago

Could you add a possibility co clear only single module, without the recursion? I have a system that has a state holding singleton and with that recursive clear it creates multiple instances of that singleton with a different state. I would like to have an option to clear it manually one by one.

omrilotan commented 5 years ago

It feels like the entire purpose of this repository is to solve the problem of recursive cleaning.

Clearing a module from cache without any parent links or children is pretty straight forward:

delete require.cache[require.resolve(<PATH_TO_MODULE>)];

Is this in your opinion a conclusion for this issue, @Dejmek ?

Kikobeats commented 5 years ago

well also could be a good abstraction.

This is my code for achieving this:

const getModuleId = item => {
  try {
    return require.resolve(item)
  } catch (err) {
    return false
  }
}

const clearSingleModule(item) => {
  const moduleId = getModuleId(item)
  if (!moduleId) continue
  if (!require.cache[moduleId]) continue
  delete require.cache[moduleId]
}

Something like clearModule.single could be helpful 🙂