Shared Modules using RequireJS

Every application needs a set of modules that are shared across all other modules. Things like String/Array helpers, Loggers etc are used across your application and it makes sense to create wrappers around them and expose them via a Common Module.

Before we start, I’m assuming that you know a bit about RequireJS. If not, I suggest you visit their website and learn about AMD (Asynchronous Module Definition).

Here is the basic folder structure that we’re going to follow. I’ll explain this in detail below:

Folder Structure

The common folder contains the individual common modules like Logger, Modal and Tabs.

  • logger.js - may contain code to output/log code either to the Console or to a third party tool like Logentries or Sentry
  • modal.js & tabs.js - may contain code to initialise, destroy, center, show, hide modals/tabs

Here is an example of logger.js that can be used to log messages. Note the use of the Singleton Pattern.

// logger.js
(function() {

	'use strict';

	define([], function() {

		var _logMessage = function(msg) {
			console.log(msg);
		};

		var _warnMessage = function(msg) {
			console.warn(msg);
		};

		var _errorMessage = function(msg) {
			console.error(msg);
		};

		return {
			log: _logMessage,
			warn: _warnMessage,
			error: _errorMessage
		};

	});
})();

Now, assume that we need to share this across different Modules (module-1, module-2, etc). Here is how we can do it:

// module-1.js
(function() {

	'use strict';

	define(['./common/logger/logger'], function(Logger) {

		Logger.log('Hello World!');

		return {};

	});
})();

If we need to share multiple common modules, we can do something like:

// module-2.js
(function() {

	'use strict';

	define([
		'./common/logger/logger',
		'./common/modal/modal'
	], function(Logger, Modal) {

		Logger.log('Hello World!');

		Modal.init('INSERT_DIV_ID_HERE');
		Modal.center('INSERT_DIV_ID_HERE');

		return {};

	});
})();

As you can see, if you have a lot of common modules, the list can grow really big really fast. It helps to consolidate all these modules into a single Common Module. Something like:

// common.js
(function() {

	'use strict';

	define([
		'./common/logger/logger',
		'./common/modal/modal'
	], function(Logger, Modal) {

		return {
			Logger: Logger,
			Modal: Modal
		};

	});
})();

And then, you can just import the Common Module file and use the helper functions using the dot notation. Here is a quick example:

// module-3.js
(function() {

	'use strict';

	define([
		'./common/common',
	], function(Helpers) {

		Helpers.Logger.log('Hello World!');
		Helpers.Modal.init('INSERT_DIV_ID_HERE');

		return {};

	});
})();

Thanks for taking the time to read this. Build something awesome!