user799755
user799755

Reputation:

How do you ensure compatibility JavaScript libraries for the browser and for node.js

I'm working with a team on a TypeScript librabry called Classical.js, and we would very much like the core module of this library to be JavaScript environment agnostic. In my mind, that means it should not only function correctly cross-browser, but also as a dependency in a node.js project.

First of all, am I missing any major JavaScript environments in my test matrix that I should be aware of?

Unfortunately no one on the team develops with node. Therefore we're not quite sure what APIs to avoid (obviously the DOM) to ensure compatibility. Are there are a standard set of GOTCHAs that node developers run into when using code that has only been tested in the browser?

One discrepancy that we did (hopefully) account for the name of the global scope, which, if memory serves me correctly, is represented by an object named global in node and window in the browser. These are the sort of GOTCHAs that we are looking for.

Upvotes: 1

Views: 258

Answers (1)

Jos de Jong
Jos de Jong

Reputation: 6819

I think you have an important issue here, one that that's currently underexposed: you want to create an isomorphic library, and you want to know which libraries you depend on are isomorphic. I think it would be a good thing when isomorphic modules would be clearly marked as such in for example npm.

There is a nice blog on this topic here: http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/

Basically, isomorphic libraries should only use functionality build in JavaScript the language itself (ES3, ES5, ES6, ...).

  • You should avoid anything related to the DOM (window, document, navigator, ...), as this is only available inside a browser environment.
  • Many core modules of node.js cannot be used in a browser (like file system, os, process, network, streams, etc). For many core modules there are browser safe versions available (for example for crypto and http). Browserify uses these versions when bundling a node.js app for use in the browser.
  • There are a lot of JavaScript engines out in the wild, implemented in all kind of languages like C, Java, Python, etc. Also running directly on hardware like Espruino. These engines may not be 100% compliant with the language specs. For example, I encountered one day that the JS engine in Java (I think it was Rhino) didn't like a variable to have the name boolean. In these cases I would argue that these engines should get better compliancy rather than you having to work around their bugs/limitations.

Anyway, there is an easy way to test whether your library is isomorphic: try to run it in both node.js and the 5 biggest browsers :)

Upvotes: 0

Related Questions