Write library for any ECMAScript environment

“It would be nice if my library can work across different JavaScript environments…” you thought.

Here is a guideline about how to achieve this goal. I’ll list the most general principles first then explain them in detail and finally give you a recommended pattern to develop this kind of library.

To make the discussion easier, we will call the ability to run on any ECMAScript environment as having zero host dependency.

When we say run on any ECMAScript environment, we mean: users of the library can run this library on a modern ECMAScript environment (at least ES2015) that supports the ECMAScript module with proper setups (e.g. provide IO functions) without modifying the library code.

Restrictions:

  1. Do not use anything that is not defined in the ECMAScript specification directly. (e.g. Web or Node APIs).

  2. Do not use module specifier ("./file.js" in import x from "./file.js") to refer to any module.

  3. Be aware of language features (eval, Date.now(), import(), Math.random(), etc…) are disabled in some special environments.

If you’re strictly following the rules described above, you’ll find that you’re almost not able to develop anything. But this article is going to introduce a comfortable paradigm for developing libraries with zero host dependency.

Read more