Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Bundling - Ignoring second JS file

I have set up a simple test using ASP.NET's bundling and minification feature. I have two very simple js files:

~/JS/Site.js

(function echo1() {
    alert("this is site.js");
})();

~/JS/test.js

(function echo2(value) {
    alert("and this is test.js");
})();

I've created a bundle as follows:

bundles.Add(new ScriptBundle("~/bundles/scripts/site-globals").Include(
    "~/JS/Site.js", 
    "~/JS/test.js"));

and referenced the bundle on the page using @Scripts.Render("~/bundles/scripts/site-globals")


When I run the site under debug (<compilation debug="true" targetFramework="4.5" /> in web.config) I get the expected result - two alert boxes show one after the other.

However, when I run change to release (<compilation debug="false" targetFramework="4.5" />) - I only see the first alert box, and the combined JS file that gets sent to the browser has completely ignored the content of test.js.

The "combined and minified" output is as below, and wrongly only includes the code from Site.js:

(function(){alert("this is site.js")})()

Any ideas on why this is happening would be much appreciated! Thanks

like image 990
Matt Wilson Avatar asked Dec 19 '12 11:12

Matt Wilson


2 Answers

I've found out what was causing this problem. If any of the javascript files have a comment as the last line, they will be combined together without a newline, causing the first line of the next file to be commented out.

Here's a link to another question on stack overflow which demonstrates this: https://stackoverflow.com/a/14223945/11459631

In my case, I was using the Web Essentials Visual Studio plugin to minify my javascript files. It was creating a .js.map file for each JS file, and at the end of each .min.js file was a commented line like this, which turned out to be causing the problem:

//@ sourceMappingURL=somefile.min.js.map

Since I didn't need the mapping files, I turned this feature off using Options -> Web Essentials -> Javascript -> Set Generate source maps (.map) to false

Hope this helps anyone who finds this problem!

like image 150
Matt Wilson Avatar answered Sep 28 '22 02:09

Matt Wilson


Matt, your bundling code looks correct, do you receive any js errors in the browser console when running in Release mode? Also as a side note, are you aware that you can simply define the folder path to your JS files and they will all be included?

like image 34
cardiac7 Avatar answered Sep 28 '22 03:09

cardiac7