Monday, April 06, 2015

Typescript: install grunt on Ubuntu

OK, I've got a Windows machine available with a shiny new install of Dev Studio, but as I generally use and Ubuntu linux box for my development work. So I set up grunt on it, and in case it's of any use to anyone here are the steps to get it up and running:

1. Install node:
    sudo apt-get install nodejs
    sudo ln -s /usr/bin/nodejs /usr/sbin/node

2. Install npm
    sudo apt-get install npm

3. Create your app structure, main directory and two subdirectories
./appName
./appName/ts
./appName/app

4. cd appName 

5. Create a README.md file with basic details in the appName directory

6. run "npm init" and fill in the project details. This will in turn create a "package.json" file which will be used later to save your project dependencies.

7. Install grunt and typescript globally:
    sudo npm install -g typescript
    sudo npm install -g grunt

8. Install grunt command line interface:
    sudo npm install -g grunt-cli

9. Install the grunt bits and pieces locally:
    npm install grunt --save-dev
    npm install typescript@1.4.1 --save-dev
    npm install grunt-typescript --save-dev
    npm install grunt-contrib-watch --save-dev
    npm install grunt-contrib-connect --save-dev
    npm install grunt-open --save-dev

10. Create a GruntFile.js which configures which directories to watch and how to generate the js files. The following is an example. Note that it does a fair bit more than simply convert the files, opening a web server and other good stuff:

    module.exports = function (grunt) {
        grunt.loadNpmTasks('grunt-typescript');
        grunt.loadNpmTasks('grunt-contrib-watch');
        grunt.loadNpmTasks('grunt-contrib-connect');
        grunt.loadNpmTasks('grunt-open');
     
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
            connect: {
                server: {
                    options: {
                        port: 8080,
                        base: './'
                    }
                }
            },
            typescript: {
              base: {
                src: ['./ts/*.ts'],
                dest: './app',
                options: {
                  target: 'es5' //or es3
                }
              }
            },
            watch: {
                files: '**/*.ts',
                tasks: ['typescript']
            },
            open: {
                dev: {
                    path: 'http://localhost:8080/index.html'
                }
            }
        });
     
        grunt.registerTask('default', ['connect', 'open', 'watch']);
     
    }

11. Run "grunt" from the appName directory. This should start a task that will watch the origin directory, and output js files whenever these change.

12. Create a ts file and test it!


With thanks to the following entries: