Skip to content

Instantly share code, notes, and snippets.

@tjwds
Last active October 6, 2019 15:16
Show Gist options
  • Save tjwds/8883b20d5981518bad66497f0466acb5 to your computer and use it in GitHub Desktop.
Save tjwds/8883b20d5981518bad66497f0466acb5 to your computer and use it in GitHub Desktop.
A poor attempt to explain the current state of dependency management in js
/* This is a template to make sure that the chart.js library is available as a global object wherever it is invoked.
* See https://devhints.io/umdjs
*/
/* Let's start by defining an IIFE with two parameters — the global context and our library. The missing docblock for
* this function would read something like "Checks the runtime environment and adds callback 'factory' (our code) to
* the application context 'global' (this). This is necessary to make sure our function is always available to be
* invoked as a new Chart(), regardless of where it's run or how it's imported."
*/
(function (global, factory) {
/* I've rearranged this to be a little easier to read. We have nested conditional operators here, which read
* condition ? executed if true : executed if false. So if our first condition is false, lines 21–26 will be executed.
*
* Here's our first question: is exports and object and is module not undefined? That means we're an ES6 module, so
* let's set our module.exports to our callback function.
*/
typeof exports === 'object' && typeof module !== 'undefined' ?
module.exports = factory() :
/* Next, let's check if we're using require.js, a dependency management library. If so, import it that way. */
typeof define === 'function' && define.amd ?
define(factory) :
/* If not, we add our callback to the global object where our code was invoked. This will be `window`, most of the
* time.
*/
(global.Chart = factory());
/* Immediately invoke this function with our two parameters: this, and the entire library. Use strict mode. */
}(this, (function () { 'use strict';
// ... now comes all the code ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment