1024px-Flatirons_Winter_Sunrise_edit_2

Our own Jonathan Creamer summarizes the article he wrote for Tech.Pro. Jonathan explores the hows and whys of using the dependency management library, Require.js, within an ASP.NET MVC Web Application. Link to the full article can be found at the end.

Traditional JavaScript includes have a few small pitfalls. First of all, the order of the scripts matters, and in order to concatenate and minify them, a third party tool has to be used to go in and replace them.

There’s the problem of globals as well. If you have two files, somefileA.js and somefileB.js. The only way for the two files to communicate is to add variables onto the global window. This is considered a bad practice and should be avoided so that your libraries do not clash with third party libraries that might happen to use the same variable names.

Require.js

Require.js is an AMD framework for the browser that helps manage dependencies and allows for the creation of small JS modules. These modules allow applications to be split up into small pieces to increase manageability and decouple pieces of the app from other parts. Below is an example of a module and how it loads in other dependencies.

This module depends on jquery, underscore, and app/foo/bar.js which is another user defined module. The order in which they are required is the order in which they are added to the callback. Whatever is returned from the module is what this module exposes as its API.

ASP.NET MVC

In an ASP.NET MVC application installing require.js is as easy as…

Then the code can be used in the _Layout.cshtml page.

The data-main points to a module that uses the require function and the require.config. The require simply retrieves a few modules and the config sets up aliases for common modules.

Read full article