Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing AngularJS Into Typescript as AMD

I am trying to follow the tutorial on github to stup a build process for typescript and angularjs. I have to be honest I am really struggling. I took the project from github and added angularjs to the bower file, the typings and the lib directory with the angular.ts file (following how JQuery was setup):

/// <reference path="../typings/tsd.d.ts"/>

var angular= angular;
export = angular;

Unfortunately, when I attempt the following I have no luck in getting my app module registered:

import JQuery = require("../lib/JQuery");
import angular = require("../lib/angular");

class A{
  public add(number1:number, number2:number):number{
    return number1+number2;
  }

  public colorBG():void{
    var app = angular.module('myapp',[]);
    $("body").css({"background-color":"black"})
  }
}

export = A;

I am seeing conflicting information online about this being type of import for angular not being possible as an AMD but the definitely typed typing file has it exported as an AMD so what gives? The gulp build process completes successfully but the call to angular.module complains it is not a function in the chrome console. Is there a trick to getting angular into typescript so I can concatenate one output file for my html? I have tried requirejs for AMD, tsify/browserify for commonjs and I cannot get either to work. Thanks in advance for any guidance.

like image 315
Shawn Avatar asked Sep 26 '22 15:09

Shawn


1 Answers

You need to:

Install type definitions for dependencies:

tsd install angular jquery --save

Install dependencies using npm:

npm init
npm install angular jquery --save

This means that your dependencies will not be under the lib folder. They will be under the node_modules folder.

Your /typings/tsd.d.ts file needs to contain references to all your dependencies:

/// <reference path="./jquery/jquery.d.ts"/>
/// <reference path="./angular/angular.d.ts"/>

Then you can reference the /typings/tsd.d.ts from your modules:

/// <reference path="../typings/tsd.d.ts"/>

import { $ } from "jquery";
import { angular } from "angular";

class A {
  public add(number1:number, number2:number):number{
    return number1+number2;
  }

  public colorBG():void{
    var app = angular.module('myapp',[]);
    $("body").css({"background-color":"black"})
  }
}

export { A };

Since TypeScript 1.5 you should use the ES6 module syntax.

Update

Since 2.0 the recomended solution is npm:

$ npm install jquery --save
$ npm install @types/jquery --save-dev

Typings and tsd are no longer required.

like image 84
Remo H. Jansen Avatar answered Oct 11 '22 14:10

Remo H. Jansen