lmccart/p5.js — pull request #466 by nasser (2014-12-30 03:10:01+00:00)
Title: Atom-Shell Support

I'm working on an [Atom Shell](https://github.com/atom/atom-shell) based framework, and I'm trying to get p5.js to work with it. It's a bit of a strange target, because it has features of both a browser (e.g. real `window` and `document` objects, and all the HTML DOM elements) and node (e.g. `require`, `module.exports`). It would be ideal if I could use the mainline p5 module off of npm, too.

I was able to get the p5.js npm module to work by making two changes:

1. Added a `"main"` entry to `package.json`
2. Manually `require`ing the `reqwest` module.

The first change is trivial, and this first commit does that. The second is trickier, and I wanted to discuss possible solutions before forging ahead.

The error I get is `ReferenceError: reqwest is not defined` pointing to line 3106 in p5.js, the invocation of the `inputfiles` function, where `reqwest` is is first mentioned at the top level.

This breaks because of how `reqwest` loads itself.

```js
!function (name, context, definition) {
if (typeof module != 'undefined' && module.exports)
module.exports = definition();
else if (typeof define == 'function' && define.amd)
define('reqwest', definition);
else
context[name] = definition();
}('reqwest', this, function () {
// reqwest definition
```

The first branch is what succeeds in Atom Shell, because `module.exports` exists. Reqwest assumes that is being `require`d from a traditional node script, and sets `module.export` to its definition. This makes it invisible the rest of the code.

In the browser, this is not a problem because there is no `module.exports` or `define.amd` (I don't think), so the third branch executes and registers a `reqwest` variable with `context`, which is `this`, which is the global object. This makes the variable visible to the later code that uses it, and everything works. This is what we want in Atom Shell as well.

In my hacking, I was able to make it work by adding `reqwest = require("reqwest");` to the top of p5.js. Deleting `module.exports` also works, but that's not a viable solution.

Options as I see them:

1. Take out pull request on reqwest to update their loading logic to take Atom Shell into account
2. Introduce a shim to p5.js that checks for a `require` function at runtime and calls `reqwest = require("reqwest");` before anything else

My experience building and managing JavaScript codebases that are expected to run in multiple contexts is very limited, so I defer to whatever you think is the best solution.