Skip to content

Instantly share code, notes, and snippets.

@humbletim
Created December 12, 2016 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humbletim/807d041d689df196e8b71a485ebf1d82 to your computer and use it in GitHub Desktop.
Save humbletim/807d041d689df196e8b71a485ebf1d82 to your computer and use it in GitHub Desktop.
Reasons to prefer `require / module.exports` in context
  • Keeps it "simple" for scripters to bring modules in.

    • "require is just an ordinary function that takes a string and returns useful stuff..."
  • Follows the "de facto" JS module standard.

    • Mainstream JS modules already support this pattern as part of the "module systems magic dance."
  • Offers a backwards-compatible, transitional way to migrate existing Script.include modules.

  • Can start with truly featherweight implementations.

    • A minimalist var api = require(url); polyfill can be realized in half-a-dozen lines of local JS code.
    • Or a similar starting point in about a dozen lines of customary ScriptEngine C++.
  • Pivots around the module free variable.

    • This extra level of indirection (module.exports vs. exports) is useful because it provides a dedicated conceptual layer for testing, troubleshooting and extending the underlying module system itself in terms of.
  • Allows for the three most common exposure patterns:

    • module.exports.foo = "bar";
    • module.exports = function clamp(obj,min,max) { [...] };
    • module.exports = { pi: Math.PI, clamp: clamp };
  • Addresses the immediate need while keeping options open for solving bigger-picture aspects later:

    • ... specialized async/sync loaders.
    • ... memoizing / caching the result of previous requires
    • ... error handling / retry strategies.
    • ... tracking and enforcing "same origin" policies.
    • ... hot reloading of modules in a dev mode.
    • ... static bundling of modules and deps into optimized .js packages.
    • ... out-of-band debugging strategies.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment