Showing posts with label typescript. Show all posts
Showing posts with label typescript. Show all posts

1/25/17

Creating My First Type Definition

Typescript Main Point

One of reasons the typescript was invented is to get javascript errors to be detected in compilation step.
For example:
If you defined function myFunc and it suppose to be called without any params, and your code use its call in multipple places:


function myFunc() {
  alert('my name is Shlomo');
}
//call
myFunc()

And after some time you decided to change function code to use the parameter:

function myFunc(nm) {
  alert('my name is ' + nm);
}
//call
myFunc('Shlomo')

In case you using javascript and you forgot to change call in some place to its new shape - you will got 'nm is undefined' error when code will try to run following call.

//call
myFunc()

in typescript After you changed myFunc definition to use parameter:

myFunc(nm:string) {
  alert('my name is ' + nm);
}
//call
myFunc()//this will not compile

If there are some calls which not using parameter left- Typescript compiler will fail.

What are type definitions?

So if you use typescript and want to use some javascript library or plugin in your code - this plugin and its methods need to be defined in a way that typescript will "recognize" it.

Experiment With Selectize

For example purposes lets take our old angular-seed project which uses typescript. To demonstrate what happen when you try to use some javascript plugin inside typescript project lets install selectize.js jquery plugin

bower install selectize --save-dev

And place the call to the plugin inside View2Ctrl controller:
As you can see - trying to use the plugin as it is made vscode angry
You can see also compilation error:

Create Starter Definition File

As we can see in other definitions - the selective definition must be hosted inside node_modules/@types directory. lets add selectize directory and add index.d.ts file inside it. I will not write here about create real definition - since guys much wiser than me already created it here,
My purpose now is only to create something that make the typescript compiler calm.


/// <reference types="jquery"/>

declare namespace Selectize {
 
}
interface JQuery {
    selectize(options?: any): JQuery;
}


As you can see - i only added selectize method to Jquery interface
That is enough for get the source compiled -

Thanks For reading

11/27/16

Export angularjs module

What are submodules?

When you writing angularjs application it is a good pattern to divide your app to submodules which are included into the main module as following:


angular.module('mainApp',['myApp.version','myApp.view1','myApp.view2'])

So it will be easy for testing or develop various parts of the application without each part need to knowing about other parts.
The directory structure of application usually place each submodule into its own directory:

.
├── view1
│   ├── view1.ts
│   └── view1.html


One of submodule "main" files contains angular module declaration:

    angular.module('myApp.view1', [
      'myApp.version.interpolate-filter',
      'myApp.version.version-directive'
    ])


How to import submodule into main typescript file?

It appears you can import code file which have no "export" syntax at all:


  //NO EXPORT AT ALL!
    angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', ($routeProvider: angular.route.IRouteProvider) => {
      $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
      });
    }])

    .controller('View1Ctrl', [() => {
    }]); 

Now in the main file - you can still use import syntax to include this code
app.ts

import './view2/view2';


Hope you have fun reading...

11/17/16

Organizing Your Angularjs Typescript Project

In one of my previous posts i found how to compile typescript files to javascript and i was very happy with myself because of my success. Since then i had little more experience with typescript. And now i have a few more points to share:

Using Import In Your Typescript Project

I have noticed many angularjs and angular2 projects using Import syntax. That way they not need to compile each file separately, instead you can compile only main file while all other files included in it (like in less or sass)
For exapmle :
Instead put all the things in your JS app.js file


//OOOOOLD STUFF.. BLAHHH
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

In typescript, you can move the config logic to its own separate config.ts file:

 export function config($locationProvider: ng.ILocationProvider, $routeProvider: angular.route.IRouteProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/view1'});
  };



and import it to app.ts main file:

/// 
import { config } from './config';///<--HERE
module angularSeed {
'use strict';

  // Declare app level module which depends on views, and components
  angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.version'
  ]).config(config)

}
 

Import Is ES6 Syntax (Not Typescript!)

So, if you need to transpile your code either from ES6 and from typescript - i cannot think about other tool than webpack.

Weeeebpaaaack....
Webpack supports ES6 natively and for get it to compile typescript you only need to include ts-loader:
 
var webpack = require('webpack');
var path = require('path');
module.exports = {
    context: path.join( __dirname, '/app'),
    entry: 'app.ts',
    output: {
        filename: 'app.js',
        path: path.join( __dirname, '/app')
    },
    resolve: {
        root: path.join( __dirname, '/app'),
        extensions: ['', '.ts', '.webpack.js', '.web.js', '.js']
    },
    module: {
        loaders: [//<-- TYPESCRIPT, COOOL
        // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: 'ts-loader' }
        ]
    }
}

Of course you need to include this webpack.config.js file in your project And update package.json with too more entries:
 
    "typings": "^0.8.1",
    "webpack": "1.13.1",
 

Build The Project

Since we using webpack now for build the project, the command to compile will be:


node_modules/.bin/webpack
 

Hope you have fun reading...
Visit my cool REPO

10/10/16

Making Angular1 Seed Project To Work With Typescript

challenge

Since typescript became more and more popular those days i decided to try and take the following challenge: To convert this angular1. seed-project from old fashioned ES5 to Typescript.
I have very little experience with typescript, and that why it is interesting. This project consist only from two basic views so it seems to be not so hard...

Typings

First we need to add typings to our project. What are those typings?
Typings are dependencies as angular or angular-routes libraries which translated to typescript
First step we need to add typescript & typings dependencies to package.json file


"typescript": "^1.8.10",
"typings": "^0.8.1",

Lets also add typings.json file which has list of Definitions of libraries we use in project

{
  "ambientDependencies": {
    "angular": "registry:dt/angular#1.5.0+20160412133217",
    "angular-route": "registry:dt/angular-route#1.3.0+20160317120654",
    "jquery": "registry:dt/jquery#1.10.0+20160417213236"
  }
}

After adding those files lets update again the package.json file so it will install typings after installing all dependencies:

...
  "scripts": {
    "postinstall": "bower install && typings install",
    ...
   }
...

Lets check - after runing npm i command the "typings" directory should appear:

Compiling

The compile command of typescript you need to call for convert your ts files into js is "tsc -p ./".
tsc takes other options of how to compile typescript from tsconfig.json file:


{
  "compileOnSave": false,
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5"
  },
  "exclude": [
    "bower_components",
    "node_modules",
    "typings"
  ]
}

It is convenient to configure package.json "scripts" zone so you can run the tsc with npm:
npm run build

..
  "scripts": {
   "build": "tsc -p ./",
    ...
   }
...

Change the code to typescript

Now you can start to convert the project to typescipt:
First - lets start with view1.js file , by rename it to view1.ts


/// <reference path="../../typings/main/ambient/jquery/index.d.ts" />
/// <reference path="../../typings/main/ambient/angular/index.d.ts" />
/// <reference path="../../typings/main/ambient/angular-route/index.d.ts" />
angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', ($routeProvider: angular.route.IRouteProvider) => {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', [() => {

}]); 

See that after running "npm run build" the view1.js file generates!

see full code here: repo
Thanks for reading

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...