saran3h
saran3h

Reputation: 14052

Sharing global between JavaScript files without using modules/exports

I have a self contained JavaScript function in one file, and some Mocha BDD tests in another file that reference it using [nodejs] require(). So in my function under test I export using module.exports. That's all well and good, in the IDE/build.

Now my function under test is actually an external virtual endpoint, which when deployed into a cloud instance, runs standalone inside a JSVM sandbox (Otto) which has no support for exports or modules, and is ES5 based (it does however embed a version of the Underscore library). If I leave the nodejs module definition in there when I deploy to cloud, it kicks off an error at runtime (as Otto doesn't recognise modules). So I want to remove it, and use some vanilla JS mechanism for the linkage back to the Mocha tests and test runner.

So my question is, if I can't use nodejs or requirejs modules, how can I link my Mocha tests in one file to a JS function in another? I had a play with placing a function closure (which most module implementations use) in the file under test, and Otto is happy with this, as its vanilla JS, but any variable with global scope in the file is still not visible from my test file, so there is no linkage.

Any thoughts?

Upvotes: 1

Views: 88

Answers (2)

saran3h
saran3h

Reputation: 14052

One of my colleague came up with a suggestion to use closure in the file under test which gets deployed into the cloud instance, if you are running under Nodejs, and conditionally do the export. I added the small anonymous closure below to do this, and Otto doesn't complain.

(function () {
    if (typeof module != 'undefined') {
        module.exports = pdp_virtual_endpoint;
    }
}());

Not sure why I didn't think about this earlier :)

Upvotes: 0

coagmano
coagmano

Reputation: 5671

From a quick look at the Otto docs, it looks like Otto only wants whole files and (as you've said) doesn't recogise commonjs modules from node.

If you've got many files I would recommend bundling them into a single file with webpack/browserify/etc, which is how most people convert modules for use in the browser, which similarily doesn't recognise commonjs modules without tooling.

Alternatively, you could convert all the module.exports to simple var declarations, concatenate the files together and hope you don't have a naming collision.

I don't see anything in the docs about having access to a window or global object to hang globals onto, which limits your options

Upvotes: 1

Related Questions