Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundling and minifying modular JavaScript (RequireJS / AMD) with ASP.NET MVC

Does anyone have any experience with or know any good solutions for bundling and minifying modular JavaScript like RequireJS / AMD in an ASP.NET MVC project?

Is the best way to use the RequireJS optimizer (perhaps in a post build action?) -- or is there something better out there for ASP.NET MVC?

like image 434
kendaleiv Avatar asked Jul 20 '12 19:07

kendaleiv


1 Answers

I think the problem you'll hit is if you used anonymous defines. If you want a combined/bundled script file that contains all your defines, you'll have to name them.

eg.

define("someModule", ["jquery", "ko"], function($,ko) { ... }); 

instead of

define(["jquery", "ko"], function($,ko) { ... }); 

If you use the file names as the module names, you'll be able to load them asynchronously (not bundled) as well as preloaded (bundled). That way you can work in debug mode as well as release mode without having to change your requires.

I have no experience with the RequireJS optimizer to know if it takes care of anonymous defines or not.

UPDATE:

I recently had to do this and one of the problems I ran into was the data-main attribute of the script tag loading require.js. Since the main.js file had dependencies on the bundled modules, they need to be loaded before main.js but after require.js. So I had to ditch data-main and load that file (unbundled) last.

from

<script src="../JS/require-v2.1.2.js" type="text/javascript" data-main="main.js"></script> 

to

<script src="../JS/require-v2.1.2.js" type="text/javascript"></script> <%: System.Web.Optimization.Scripts.Render("~/bundles/signup") %> <script src="main.js" type="text/javascript"></script> 

I haven't looked, but if the bundle configuration could ensure main.js is last, then wouldn't even need that last script tag.

like image 60
Jeff Shepler Avatar answered Oct 26 '22 13:10

Jeff Shepler