Adding external javascript to Ionic 2 project

855 views Asked by At

Lets say I have this foo.js file where I declared a variable, a function and a class.

It is not in the project yet.

Now assume I want to use this variable, class and function in my home.ts method, or just make it globally available (to use in a home.ts method).

How can I make it happen?

2

There are 2 answers

2
Mohan Gopi On

lets say in your foo.ts file we have a funtion

myfunt(){
//your logic goes here
}

now if you want to make use of this function in home.ts file the

step1: import your foo.ts file in home.ts

step2: in your export class should look like this

    export class home extends foo { 
//since you have used extends keyword now you unlocked all the data in foo.ts file for home.ts file


        //here now try to access your myfunt() funtion


        constructor(){

           super.myfunt(); //user super keyword to access all the data available in foo.ts file
        }

    }
3
jordins On

You can use definition files (.d.ts).

First, check if foo.js have already a definition file created by the community. Check it here: http://microsoft.github.io/TypeSearch/ or here https://github.com/DefinitelyTyped/DefinitelyTyped

If it exists you can install it like this:

npm install --save @types/foo

If not, you can create your own definition file for this javascript file.

Let call it foo.d.ts with a content like this:

declare var data:any;
declare function myFunc(n:string);

Once you have it you can use it like a normal ".ts" file.

import * as foo from "./foo"; //"./foo" is the path of your .d.ts.
foo.myFunc()

More information here: https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/