Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Last active December 21, 2015 14:48
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 alexeyraspopov/6322025 to your computer and use it in GitHub Desktop.
Save alexeyraspopov/6322025 to your computer and use it in GitHub Desktop.
The most simpliest and shortest JavaScript module system

What?

require=function(a){return function(b){var c={};return a[b]||this[b](c)||(a[b]=c)}}({});

Just 88 characters without any 3rd-party libraries and build scripts.

Readable version:

require = (function(cache){
  return function(name){
		var exports = {};
		return cache[name] || this[name](exports) || (cache[name] = exports);
	};
})({});

Example

All modules are simple functions which are parsed at pre-execution stage, when the browser prepares to execute the code.

Module definition:

// moduleA.js
function moduleA(exports){
  exports.pew = function(message){
    console.log(message);
  };
}

Module usage:

// initial.js
(function(){
var module = require('moduleA');

module.pew('message');
})();

Scripts including:

<script src="require.js"></script>
<script src="moduleA.js"></script>
<script src="initial.js"></script>
require=function(a){return function(b){var c={};return a[b]||this[b](c)||(a[b]=c)}}({});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment