Manually resolving require-function


#1

I need to dynamically require a module during runtime and resolve this require manually. Here is what I tried:

From a BrowserWindow I am requiring a module A like this: require('./path/to/moduleA.js') which works fine. In the required moduleA I have another require statement to require moduleB which I need to resolve manually.

I tried to overwrite the global require function inside of my BrowserWindow like this:

window.oldRequire = window.require;
window.require = src => src === 'moduleB' ? /* resolve manually */ : window.oldRequire;

In moduleA I can now call global.require('moduleB') and my manually resolved module works, but require('moduleB') doesn’t work. Is there a way to manually resolve modules in electron?


#2

Why don’t you just write a helper function resolve(module: string): string, where you can do:

const resolve = require('./helpers/resolve')
const moduleA = require(resolve('moduleA'))

Not sure why you would want to override Node’s require to do that?


#3

Thanks for your help. I don’t want to change the code in moduleA, so I don’t want to change the require statement there. It still should only say require(moduleB) but it should be resolved manually as it fails otherwise.


#4

I don’t think it’s possible, nor a good idea, to override Node’s require function.