If you like to include a global js file (e.g. library) and encapsulate it in your angular2 (ng2) you have several options:
Option 1:
You might find its *.d.ts file in here https://github.com/DefinitelyTyped/DefinitelyTyped and also it is recommended to look here: https://microsoft.github.io/TypeSearch
If you found its @type you should install the library (e.g. npm install --save theLib.js) and install the @type you have found --> Once it is installed you can import the library via your code (e.g. import * as theLib from 'theLib';)
Option 2:
If you can't find it you may try to generate d.ts file. For example if you have your own library that exports a class of some kind. You might want to use the following tool to generate d.ts file: https://github.com/Microsoft/dts-gen
Once d.ts is generated you should include it in your tsconfig.json file (under "files" key)
Option 3:
In case of 3rd party library that suppose to be included as global var in your app (like jquery) but there is no @type anywhere you can include it as follow:
- Download the library (any way you find fit)
- Include a script tag in your index.html to load the library
< script src="../node_modules/myExtLib/dist/myExtLib.js">< /script>
- Add
global.d.ts next to tsconfig.json and add the object declaration to it. For example if myExtLib.js create a global var myExtObj:
declare const myExtObj:any;
- Add the following to tsconfig.json if not exists
"files": [
"global.d.ts" ]
Now you can access myExtObj globaly.
I personally don't like such global variables so I create a service that reference it and then remove it from global namespace as follow:
The service
import { Injectable } from '@angular/core';
function getWindow():any {
return window;
}
@Injectable()
export class MyExtObjRefService {
private _myExtObj:any;
constructor() {
let window = getWindow();
this._myExtObj = window.myExtObj;
window._myExtObj = null;
_myExtObj = null;
}
get myExtObj() {
return this._myExtObj;
}
}
Don't forget to declare it in the module's providers
Now you can access myExtObj from any component by importing the service and call myExtObjRefService.myExtObj without worry that you have junk in your global namespace.