Miniature Javascript not working when concatenated into one file
I have 3 JS libraries that I am using which are in their own separate files. They are commented out with code abbreviated in each separate file
file 1: http://jsfiddle.net/NGMVa/
file 2: http://jsfiddle.net/AzEME/
file 3: http://jsfiddle.net/qVkhn/
Now individually they work fine in my application, don't throw any errors. But I wanted to upload fewer files, so I combined them into one file like this: http://jsfiddle.net/Gxswy/
However, in Chrome, it throws an error on the last line of the file:
Uncaught TypeError: undefined is not a function
and then it doesn't work anymore. I didn't change anything in the code before I merged them, I just copied and pasted the contents of the first three files into the new one and it doesn't work anymore. Don't understand why combining them into one file seems to break functionality
Did anyone want to understand what's going on here?
source to share
Make sure to add semicolons at the end of each file or concatenate, and then minify and minifier should take care of that.
Try this code: https://gist.github.com/elclanrs/4728677
source to share
Cause
In my case, it was because I set the dependencies in requirejs
shim
, for the library ( perfect-scrollbar
), which already supports AMD loading. The result is that all of its code is define
bypassed after it has grunt-contrib-requirejs
done its job.
Basically, for file sharing requirejs grunt-contrib-requirejs
would be
// change this:
define(['d3'],function(d3){...});
// into this:
define('d3', ['d3'],function(d3){...});
While inside perfect-scrollbar
already exists
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory); // <-------------------------- this part
// after minification would become:
// define('PerfectScrollbar', ['jquery'], factory);
} else if (typeof exports === 'object') {
factory(require('jquery')); // Node/CommonJS
} else {
factory(jQuery); // Browser globals
}
}(function ($) {
// perfect-scrollbar code here...
});
Which was contrary to what I pointed out in shim
:
shim: {
"PerfectScrollbar": ['jquery', 'jquery.mousewheel']
}
Therefore, when requirejs
he got to the part where he PerfectScrollbar
was really identified, he jumped over it, assuming that he had already completed the task.
Decision
Don't include dependencies in shim
for libraries that already have AMD support.
Question
But what if I need to specify dependencies? I need jquery.mousewheel
on top of jquery
which is already specified in his code.
Answer
Require a file with a proper requirement and its own dependencies correctly:
define(['perfect-scrollbar', 'jquery.mousewheel'], function(){...});
Or when an AMD supported library is needed,
// inside jquery.mousewheel:
require(['jquery'], factory);
Or is it not
shim: {
"IDontSupportAMD": ['jquery']
}
source to share