#Use Grunt to concat and minify AMD modules and templates
##About
This is an example Gruntfile to concatenate and minify AMD modules and templates. This can be used both for custom code and for existing AMD modules. For instance, the concat:esri
task above can be used to concatenate a series of esri AMD modules that aren't included in init.js
and would otherwise be loaded separately.
##To use The Gruntfile should be changed to reflect individual projects' file strucutres. This particular implementation expects a file structure of:
package.json
Gruntfile.js
index.html
js/
main.js // application entry point, with locationPath and packages
app/
widgets/
lib/
Make sure Grunt is installed globally.
In the root directory of the project, run npm install
then grunt dev
to get a concatenated, unminified version of all the AMD modules and templates.
To concat and minify the modules, run grunt build
.
To pull down the entire esri api, run grunt esri
. After pulling down the api, this will concatenate all the modules listed under the concat:esri task. grunt esri
only has to be run once. When the module list is changed, grunt dev
will re-concatenate the esri modules as well as the app modules.
##Background and structure of concatenated file Looking at a formatted version of http://js.arcgis.com/3.12/init.js, one can see the structure of a concatenated series of AMD modules is:
require({
cache: {
'path/to/js/module': function() {
module code
},
'path/to/js/module2': function() {
module2 code
}
...
}
});
Additionally, html templates could be included in this cache (seen at the bottom of init.js
):
require({
cache: {
// lots of js modules...
...
// html templates:
'url:path/to/html/template': '<div class=...',
'url:path/to/html/template2': '<div><div id=...'
}
});
Thus, the Gruntfile above uses the concat task, its banner, footer, and separator options, and its individual file processing to recreate this structure.
##TODO
Currently a script tag for js/main.js
, the entry point into the application, is required in index.html. Additionally, main.js doesn't use the cached modules in js/compiled.js -- it loads the modules individually. In this particular application, main.js only needs one module, so it's not that big a deal. However, it seems like there should be a way to automatically trigger main.js to run. I've tried putting the contents of main.js in a script tag in index.html, and I've tried including main.js in compiled.js and then requiring main from index.html. Neither of these have worked, but I'm still thinking about it...