Search code examples
javascripttypescriptgruntjsgrunt-contrib-watch

Typescript & Uglify Tasks


Ok, so I am playing around with typescript and was hoping to use it to minify my code but as I understand it, typescript does not do that. So I I built my Gruntfile like this,

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    ts: {
      default: {
        files: {
          '/js/builds/admin.js': ['/typescript/admin/*.ts'],
          '/js/builds/main.js': ['/typescript/main/*.ts'],
          '/js/builds/public.js': ['/typescript/public/*.ts']
        }
      },
      options: {
        fast: 'never',
        sourceMap: false
      },
    },

    'uglify': {
      options: {
        preserveComments: 'some',
      },
      my_target: {
        files: {
          //Libs Files
          '/assets/js/libs.js': [
            '/js/libs/jquery-3.1.1.min.js',
            '/js/libs/underscore-1.8.3.min.js',
            '/js/libs/backbone-1.3.3.min.js',
          ],

          //Plugin Files
          '/assets/js/plugins.js': [
            '/js/plugins/alertify.min.js',
          ],

          //Admin Build
          '/assets/js/our_admin.js': [
            '/js/builds/admin.js'
          ],

          //Main Build
          '/assets/js/main.js': [
            '/js/builds/main.js'
          ],

          //Public Build
          '/assets/js/public.js': [
            '/js/builds/public.js'
          ]
        }
      }
    },

    watch: {
      'TypeFiles': {
        files: ['/typescript/**/*.ts'],
        tasks: ['ts'],
        options: {
          spawn: false
        },
      },

      'JSFiles': {
        files: ['/js/**/*.js'],
        tasks: ['uglify'],
        options: {
          spawn: false,
        },
      },
    }
  });

  grunt.loadNpmTasks("grunt-ts");
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
};

and what I was trying to do was get typescript to build into standard javascript and then auto run the my uglify task.

As it stands, it works if I added / edit any lib or plugin files (as they have nothing to do with my typescript) but when I edit the typescript files, it will build the JS files, but not run the uglify task?

So how do I get it to do the uglify task after the ts task is completed?

Many thanks.


Solution

  • I think I have a solution to this issue. I added the TS task to my JSFiles watch task and added the typescript files to the list of files it should watch for, like so:

    'JSFiles': {
      files: ['/js/**/*.js', '/typescript/**/*.ts'],
      tasks: ['ts', 'uglify'],
      options: {
        spawn: false,
      },
    },
    

    Now this might to be the best option, as it will take some time to complete the typescript and the minify tasks. But I have set this project up in Symfony2 and I prefer to set up my new project pointing to the prod. files.

    Thanks