Just as we minified and concatenated our style sheets, we shall now go ahead and minify and concatenate our JavaScript files. Go ahead and take a look at grunt-contrib-uglify
. Visit https://github.com/gruntjs/grunt-contrib-uglify
for more.
Install this by typing:
sudo npm install grunt-contrib-uglify -save-dev
And, as always, enable it by adding grunt.loadNpmTasks('grunt-contrib-uglify');
to our Gruntfile.js
. Next, create a new task:
"uglify": { "target": { "files": { "dist/src/js/myphoto.min.js": ["src/js/*.js"] } } }
Running grunt uglify
should produce the following output:
The folder dist/js
should now contain a file called myphoto.min.js.
Open it and verify that the JavaScript code has been minified. As a next step, we need to be sure that our minified JavaScript file will actually be used by our production-ready index.html
. We will use grunt-processhtml
, which we installed in the previous section. All that we need to do is wrap our
link
tags inside a special build comment: <!-- build:js js/myphoto.min.js ->
:
<!-- build:js js/myphoto.min.js --> <script src="js/alert.js"></script> <script src="js/carousel.js"></script> <script src="js/a11yhcm.js"></script> <!-- /build ->
Next will add our uglify
task to our watch
task list:
"watch": { "target": { "files": ["src/styles/myphoto.css"], "tasks": ["uncss", "cssmin", "processhtml", "uglify", "copy"], } },
Golden rules when working with Grunt When developing a Grunt file (or any build file for that matter), there are a few practices that you should keep in mind:
dist
folder should not contain any unprocessed source files.
src
is the "unprocessed" code,
dist
is the result of "processing"
src
to create a distributable.
dist
directory. You should also create a Grunt serve
task to run the appropriate tasks for a development server, with the
watch
task being the final task that is run.
watch
task should be watching all source files. In our case, we watched just one, in order to keep the example simple and easy to understand.