Grunt Watch and Uglify
Category:
Let's say we have a directory structure like so:
build/ node_modules/ src/*.js Gruntfile.js package.json ...
And all of our project's source code lives in the src directory:
src/hello.js src/world.js
We'd like all of the code from these files to be compiled down and uglified into this file:
build/hello-world.js
Except everytime we make a change to a file in the src directory, we don't want to manually uglify the code into a single file. We can watch for changes to our source code, and automatically uglify it with a Grunt watch:
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: 'src/*.js', dest: 'build/<%= pkg.name %>.min.js' } }, watch: { files: ['src/*.js'], tasks: ['uglify'] } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); // Default task(s). grunt.registerTask('default', ['watch']); };
If we use a Gruntfile.js like the one above, we'll save ourselve's lots of time! Now just navigate to your project directory and run grunt:
cd my-app grunt