When incorporating external libraries into your project, there are two essential components to consider. Firstly, you need the JavaScript code that will enable the functionality of the library, and secondly, you need the definition files to provide the IDE with the necessary type information.
Ensuring that the JavaScript code is included is crucial for the proper functioning of your application. The simplest way to achieve this is by including the third-party library using a <script src="thirdLib.js">
tag in the HTML file hosting your Angular 2 app. While this method will allow your app to work, it does not provide IDE support. To prevent IDE errors related to undefined variables like 'thirdLib,' you can add declare var thirdLib:any
to your TypeScript file. Although this approach lacks auto-completion for 'thirdLib,' it prevents IDE issues.
If the library was developed in TypeScript, you can import both the executable code and type definitions by referencing its TypeScript file using
import {thirdLib} from 'thirdLibfolder/thirdLib'
in your code.
In cases where the library is not written in TypeScript but has a separate thirdLib.d.ts definition file available, you can reference this file in your TypeScript code using
/// <reference path="thirdLibfolder/thirdLib.d.ts" />
. Additionally, include the actual JavaScript code through a script reference as mentioned earlier.
The specific locations of these files and whether you include extensions in the references depend on your project configuration and the bundler or build tool being utilized. For instance, webpack searches the node_modules
folder for imported libraries and accepts references with or without the .ts
extension. Conversely, Meteor may throw an error if the .ts
extension is included.
For further information, refer to:
https://github.com/angular/angular-cli/wiki/3rd-party-libs