Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite or Overload a node_module name path

Assume i have a installed node_module called magicalModule and I have installed it via npm i magicalModule.

I import it into my code via const magic = require('magicalModule').

Is there a way for me to overwrite that specific path so that I can use my own module instead?

For example I have a modified version of that module that I want to use instead of the installed package. Maybe place something in package.json or something like:

dependencies:{
    Alias:{
         'magicalModule': process.env.local ? './myPath' : 'magicalModule'
    }
}

Something like above...

I know that there is a module called Module-alias but I'm not sure if it fits my use case.

As to why I would need to do something like this is because there is an NPM package that is used alot in multiple files and I want to replace it with another NPM package that I'm currently developing. Wanna test it locally before publishing that NPM package...

like image 718
mr Potato Avatar asked Dec 13 '25 21:12

mr Potato


1 Answers

If you need dynamic import then put require in an if condition

let myModule = require(process.env.local ? './myPath' : 'myModule'); // make sure there is index.js inside

You cannot do it in package.json as that file is static. However if you can somehow edit package json then local dependencies can be added like

"dependencies": {
    "bar": "file:./myPath" // package.json is read inside of ./myPath
  }
like image 137
bugwheels94 Avatar answered Dec 16 '25 13:12

bugwheels94



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!