Tutorial – Getting started with TypeScript and Cocos2d-x JS- Part 1 – Hello World

Tutorial – Getting started with TypeScript and Cocos2d-x JS- Part 1 – Hello World

This is part 1 of the tutorial series Getting Started with TypeScript and Cocos2d-x

Goals:

  • When dealing with multi-platform games, we need code that will work in both the browser and the Cocos2d-x jsb engine
  • Ideally, we want all of our TypeScript to be compiled into a simple uglified and minified js file
  • We want to debug our TypeScript within the browser
  • We want to preserve the integrity of our Cocos2dx project structure
  • We want to run offline unit tests on our code
  • We want to run online unit tests on our code

Suggested Workflow

I have found it beneficial to test Cocos2d-x JS code within the browser as I develop. I also test on other target platforms (IOS/Windows) regularly so that I may quickly expose and fix any bugs caused by incompatibilities between jsb and Cocos2d-x web APIs (of which there have been a few).

I started out with Cocos2d-x JS development under WebStorm but after turning to TypeScript I have found Visual Studio Code to be superior in terms of performance and general workflow.

Preliminary checklist

  1. Install npm
  2. install typescript; run the command: npm install -g typescript
  3. Install a suitable editor.  Visual Studio Code (recommended)
  4. Install Cocos2d-x
  5. Install git (optional, recommended)

Grab the Source

You can use the command below to clone the completed example projects from GitHub:

git clone https://github.com/dalste/starting-typescript-and-cocos2dx.git

 

Note the node_modules and typings folder have been ommited via a .gitignore file. As a result, we are required to resolve dependencies for each project prior to performing a build.

You can resolve your node and typings dependencies by executing the below commands where appropriate:

npm install

typings install

Getting started and Hello World

Please ensure that you have completed all of the steps in the preliminary checklist before continuing.

Create a root folder for your project. The exact name doesn’t matter, but for our purposes, we will call it MyProjectName.

We need some folders for our TypeScript and js files: a common approach is to name mentioned folders src and dist, but in our case,  src will be reserved for our Cocos2d-x JS project source code.

Navigate to the folder you created above (the project root), and execute the following commands:

mkdir tssrc

mkdir tsdist

Now, let us initialise the project for node.

npm init

The npm init command will guide you through a bunch of options, for the most part you can use the defaults; you can always edit the resulting package.json at a later date. Use ./tsdist/main.js for the entry point.

The resulting project directory should look something  like this:

MyProjectName/
             ├─ tssrc/
             ├─ tsdist/
             └─ package.json

We will be using gulp to handle builds, typescript for coding, and gulp-typescript to tie the two together, so we need to install the appropriate dependencies.

Execute the following commands:

npm install -g gulp-cli
npm install –save-dev typescript gulp gulp-typescript

For more info please see https://www.typescriptlang.org/docs/handbook/gulp.html

Now here is where we will deviate from the norm. Most modern TypeScript guides will use external modules,  but for our purposes and to simplify the compatibility with Cocos2d-x jsb we will use namespaces and triple slash directives. A more thorough discussion of the choice between external modules and namespaces is given in part 2.

With that said, let us create some code:

Navigate to tssrc and create a file named greet.ts and insert the following code:

namespace typescriptbase {
    export function sayHello(name: string) {
        return `Hello from ${name}`;
    }
    
}

In the same folder create a file named main.ts and insert the following code:

/// <reference path="./greet.ts" />
namespace typescriptbase {
        import sayHello = typescriptbase.sayHello;

        console.log(sayHello("TypeScript"));
}

In the project root, MyProjectName, create the file tsconfig.json and insert the following:

{
    "files": [
        "tssrc/main.ts"
    ],
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es5",
        "module": "none",
        "outFile":"main.js"
    }

}

Now we need Gulp. Gulp will allow us to create powerful build scripts.

In the project root, create a file name gulpfile.js and insert the following:

var gulp = require("gulp");
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");

gulp.task("default", function () {
    return tsProject.src()
        .pipe(tsProject())
        .js.pipe(gulp.dest("tsdist"));
});

For more info please see https://www.typescriptlang.org/docs/handbook/gulp.html

Ok, now its time to test the project.

Navigate to the project root and execute the below commands:

gulp
node tsdist/main.js

You should see the following output in the console:

“Hello from TypeScript”

Your file structure should look something like this:

MyProjectName/
             ├─ tssrc/
             ├─ tsdist/
             ├─ node_modules/
             ├─ gulpfile.js
             ├─ tsconfig.json
             └─ package.json

 

You should  now have a basic Hello World TypeScript project set up.

The completed project example typescript-cocos2dx-hello-world can be found as a subfolder of the GitHub repository.
Stay tuned for parts 2, 3 and 4 of this series where we will look at integrating tslint, mocha, and Cocos2d-x JS

 

 

Command Line Quick Reference

#when run from a project directory will execute the tasks specified within gulpfile.js
gulp

#initialises a folder into an npm package
npm init

#resolves all --save-dev dependencies for a package/project into the node_modules folder
npm install

#installs typescript globally into npm
npm install -g typescript

#installs gulp command line utility
npm install -g gulp-cli

#the --save-dev switch instructs npm to install gulp, typescript and gulp-typescript as dependencies for your project
npm install --save-dev typescript gulp gulp-typescript

#installs gulp-tslint lint as a dependency for your project
npm install --save-dev gulp-tslint

#installs tslint as a dependency for your project
npm install --save-dev tslint

#instructs node runime to run the main.js file
node tsdist/main.js

#installs typings cli
npm install typings --global

#installs typings for mocha
typings install dt~mocha --global --save

#installs mocha for gulp
npm install --save-dev gulp-mocha

 

References:

https://www.typescriptlang.org/docs/handbook/gulp.html

http://stackoverflow.com/questions/35470511/setting-up-tsconfig-with-spec-test-folder

 

 

 

 

One Reply to “Tutorial – Getting started with TypeScript and Cocos2d-x JS- Part 1 – Hello World”

Leave a Reply

Your email address will not be published. Required fields are marked *