felixge / node-sandboxed-module

A sandboxed node.js module loader that lets you inject dependencies into your modules.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Globals don't propagate to required modules

domenic opened this issue · comments

I was trying very hard to do

var domify = sandboxedModule.require("domify", { globals: { document: myFakeDocument } });

But domify resolves to /node_modules/domify/index.js, which is just

module.exports = require('./lib/domify');

But if I insert a console.log(document) at the top of /node_modules/domify/lib/domify.js, it fails, indicating the document global didn't make it through the dependency chain.

Any ideas on how to do this @felixge or @domenic? It would be really handy!

I gave it a shot, but it's pretty tricky. You basically need to inject some kind of sandboxed module require into the sub-dependencies, but that's not easy to do with the current codebase.

You can work around it like so:

var domify = sandboxedModule.require("domify", {
  globals: { document: myFakeDocument }
  requires: {
    "./lib/domify": sandboxedModule.require("domify/lib/domify", {
      globals: { document: myFakeDocument }
    })
  }
});

(it might be "domify/lib/domify" instead of "./lib/domify", not sure.)

Ah, the exact same workaround I'm currently hacking on. It'll do for now. Thanks mate

We recently added this feature to proxyquire.

I'm not sure if that helps you at all since it works with require extensions (so may not apply here), but I thought it might help you to have a look.

If you prefer to not read diffs, it all happens in here.