Titanium

Introducing Titanium Boilerplates for TypeScript

We just finished the first series of Titanium boilerplate projects for modern app development, starting with full support for TypeScript in both Alloy and classic apps.

Yep, that’s right, you can integrate TypeScript into any app project, new or existing, and, in this blog post, you will learn how easy it is.

Getting Started with our Templates

Integrating TypeScript with Titanium is pretty straightforward. All that is required is the TypeScript compiler and a CLI plugin that will compile your .ts files down to JavaScript.

To get you started quickly with TypeScript, we have prepared two example apps:

You can also find them in our new titanium-boilerplates repository on GitHub.

These are simple greeter app examples written in TypeScript that is already setup with typings for all Titanium APIs, including Alloy, a base configuration for TypeScript, and linting using TSLint.

It is a great starting point for your new TypeScript-enabled app project.

TypeScript Support for Existing Projects

Enabling TypeScript support in your existing project is also done in a few simple steps.

1. Install TypeScript Compiler

First, you need to install the required dependencies via npm right into your project root. To save your installed dependencies, create a minimal package.json with the following content (if your project does not already have one):

{
  "name": "my-typescript-app",
  "version": "1.0.0",
  "main": "index.js",
  "private": true
}

 

Now install the TypeScript compiler and the required typings for Titanium and save them to your dev dependencies.

npm i typescript @types/titanium -D

 

2. Create tsconfig.json

After this, create a tsconfig.json for your project. The configuration slightly differs depending whether you use Alloy or a classic project.

For Alloy projects, the tsconfig.json looks like this:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": [
        "*",
        "app/lib/*"
      ]
    },
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es2015",
      "es2015.iterable"
    ],
    "downlevelIteration": true,
    "strict": true,
    "esModuleInterop": true,
    "noImplicitAny": false
  },
  "include": [
    "app/**/*"
  ]
}

 

In classic projects, you can omit the `paths` compiler options and need to adjust the include setting to Resources/**/*.

The compiler settings are just reasonable defaults, and you can adjust them depending on your needs.

ALLOY ONLY: Copy Alloy Typings

Alloy currently does not provide typings on its own But, you can copy the typings from the Alloy boilerplate project. Copy the globals.d.ts file over to your project’s app folder.

3. Migrating your JavaScript Files

Now you can start migrating your JavaScript files. Don’t worry though – in the first step, you won’t have to touch any of your code. However, it is required that you rename at least one .js file to .ts. Otherwise the TypeScript compiler would complain that there are no input files.

Of course, this might not feel right. You didn’t really migrate anything, yet. We recommend reading through Migrating from JavaScript for further guidelines how to continue from here.

4. Installing the Pre-compile Hook

Last, but not least, is the CLI hook that actually triggers the compilation of the TypeScript files. Create a new file hooks/pre-compile.js in your project and paste the following content to it:

'use strict';

const path = require('path');
const spawn = require('child_process').spawn;

exports.id = 'ti.typescript';
exports.init = (logger, config, cli) => {
  cli.on('build.pre.compile', {
    priority: 900, // explicitly lower priority to make sure this hook runs before the Alloy compiler
    post: (builder, callback) => {
      const tscPath = path.resolve(__dirname, '..', 'node_modules', '.bin', 'tsc')
      const args = [ tscPath ];
      logger.info('Compiling TypeScript files');
      logger.trace(`Executing: node ${args.join(' ')}`);
      const child = spawn('node', args, {
        stdio: 'inherit',
        cwd: cli.argv['project-dir']
      });
      child.on('close', code => {
        if (code === 0) {
          callback();
        } else {
          const error = new Error(`TypeScript compiler exited with non-zero exit code ${code}`);
          error.code = code;
          callback(error);
        }
      });
    }
  });
};

 

That’s it! You can now use TypeScript in your Titanium project. Feel free to ask your questions in a comment to this blog post, on
StackOverflow (using the #titanium keyword) or join our TiSlack community.

Code strong!