Question

I've been catching up with the modern client-side JS ecosystem and reading up on module systems such as CommonJS and AMD (incl. associated tools - browserify, requirejs, onejs, jam, dozens of others). If I'm writing a Javascript library, how do I package it such that it can be most broadly accessible (ideally by users who swear by CommonJS, AMD, and especially neither)?

Popular libraries like jQuery seem to just use old-school file concatenation for building itself and dynamically detect whether it should write to an exports or the global context. I'm currently doing the same thing, but the main downside is that if I (unlike jQuery) depend on a few libraries, it's nice to not have to ask users to manually pre-include the transitive set. (Though I currently just have two dependencies.) And of course global namespace pollution.

Or perhaps it's cleanest to generate multiple versions of my library, for each context?

This also affects packaging and publishing. There are several systems, but I believe the major one is bower, which is easy to deal with since all it does is fetch. However, if I want to package it up for component, then that requires a CommonJS module.

Are there other relevant aspects I should be aware of? Are there any good example projects to follow for all of this?

Était-ce utile?

La solution

I have been thinking about this myself and I came to several conclusions:

  1. Create one version of the framework that can be used in both global and AMD setting
  2. Don't obsess over having to ask your clients to include dependencies manually, it is a one-per-project activity and should be done anyway, whether you provide an AMD-packaged or global-scoped framework (3rd party dependecies placement will have to be adjusted anyway, is what I am saying)
  3. I use Grunt for project building/packaging/testing/linting/whatever, so for all other packaging alternatives I have different tasks.

So, in short, build for "old-school/AMD" first, package for "new-age" later.

P.S.

I am also a firm believer that your packaging and delivering process/need shouldn't (whenever possible) dictate your architectural and development decisions.

I try to build the most customizable, modular and usable code I can, while using the packaging paradigm of my choice, then I consider alternative packaging. If I succeeded in the first part, second one is normally either straight-forward or requires very little codebase changes (because of the modularity and proper principles application in the first step).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top