-
Notifications
You must be signed in to change notification settings - Fork 298
Documentation for customRequire
option
#461
Comments
Like the comment says new NodeVM({
require: {
builtin: ['producer'],
customRequire: (id: string) => {
if (id === 'producer') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return producerFuncs
}
}
}
}) |
I implemented what you suggested, but still getting the same error. |
Sorry, I was wrong here. Only actual built-ins are allowed in the new NodeVM({
require: {
mock: {
producer: producerFuncs
}
}
}) |
Thanks! Would you consider this an idiomatic way to perform dependency injection? My hope was that there was a way to directly specify the source code of the producer as a module dependency, but it doesn't seem like that's possible without writing it to a file and listing it as a |
Since it is currently not possible to give strings as sources instead of loading from files I would do it like this: const { NodeVM, VMScript } = require('vm2');
const kVM = Symbol('vm');
const inject = {
producer: new VMScript('exports.x = 1;'),
};
function makeInjectionProto(inject) {
const proto = { __proto__: null };
for (const key of Object.keys(inject)) {
proto[key] = {
configurable: true,
enumerable: true,
get: function () {
return this[kVM].run(inject[key]);
},
};
}
return proto;
}
const proto = makeInjectionProto(inject);
function onNewInstance() {
const mock = Object.defineProperties({}, proto);
const vm = new NodeVM({
require: {
mock
}
});
mock[kVM] = vm;
console.log(vm.run('exports.x = require("producer");'));
}
onNewInstance();
onNewInstance(); |
Got it! Thanks. |
Looking for some clarification around the
customRequire
option inNodeVMOptions
. From what I gather, thecustomRequire
option of type(id: string) => any
takes the name of the module being required and returns an object containing the functions that the require is intended to import. But, for some reason, my providedcustomRequire
function is never being executed.My simplified use case is as follows. I have strings representing two typescript source files representing the API producer:
and the API consumer
Then I'm transpiling them to JS using the TS compiler API, which produces
and
respectively. But when I run
I get
VMError: Cannot find module 'producer'
. Any idea why this might be happening?The text was updated successfully, but these errors were encountered: