How to set a default/fallback scope on package names with Node require()

742 Views Asked by At

I am using a particular module in my Node code:

const example = require('example');

However this module is slow to be updated, so I have forked it and published it with my updates under my own scope on npmjs.com. However now to use my own module, I must change every use in my code:

const example = require('@my-username/example');

The problem with this is that I will have to commit a bunch of changes throughout many files to rename the module, then when upstream merges my changes into the official version I will have to update my code again to remove the scope operator from require() across all those files, then add it back if I have more changes that are slow to be accepted, and so on.

Is there a way that I can tell Node or NPM that if require() can't find a module with no scope in the name, to then check all the @scope folders in node_modules to see if there's a match there?

If that were possible then I would only need to update package.json with the relevant package version and the code itself could remain unchanged as I switch between my fork and the official version.

1

There are 1 best solutions below

0
Manuel Spigolon On

you can implement it using module-alias

This will slow down your startup, but let you write all this logic for every requires you make in your application.

const moduleAlias = require('module-alias')

// Custom handler function (starting from v2.1)
moduleAlias.addAlias('request', (fromPath, request, alias) => {
  console.log({
    fromPath,
    request,
    alias,
  });

  return __dirname + '/my-custom-request'
})

require('request')