Using and including a 3rd party JavaScript library in an Ionic 2 and Angular 2 [typescript] application image 7

Using and including a 3rd party JavaScript library in an Ionic 2 and Angular 2 [typescript] application

While working on a Ionic 2 (and Angular 2) application, I needed to make use of a 3rd party library (exif – https://github.com/exif-js/exif-js – to be exact, a JavaScript library for client side image analysis). This article describes the few steps I learned I had to go through in order to include that library in my application and use it in my [typescript] code. Note: this X-Team blog article showed me the way, after I read many internet resources that did not help.

1. Download the JS library and add it to the www directory of the Ionic 2 application

image

2. Add a script tag – to load the JavaScript file – in the index.html file in [that same] directory www

SNAGHTMLcd2aad2

3. In every TS file in which you want to use the library, declare a variable of type any and with the name of the function from the 3rd party library – to act as a placeholder for the 3rd party JS library. During compilation, the real 3rd JS library is not visible, so any direct references to it will cause errors unless there is such a placeholder as shown here. Because the 3rd party library is loaded by the index.htm- the main page in the single page application – its functions will always be available (no lazy loading) and the references to the placeholder become references to the real library as a result.

The next figure shows how I did this for the exif library. Its main object is called EXIF, so my placeholder has that name. In the typescript function I can refer to functions that I know exist on  EXIF – and I do not get compilation errors (nor of course do I get code completion or type safety). At runtime the references to EXIF are satisfied because then the exif.js file has been loaded.

 

image

 

Resources

Ionic 2 and External Libraries – good overview of including JavaScript libraries that are offered as node  module and for which typesettings are available – http://mhartington.io/post/ionic2-external-libraries/

Include JavaScript Libraries in an Ionic 2 TypeScript Project (including JavaScript libraries for which no node module and/or type settings exist) – http://x-team.com/2016/06/include-javascript-libraries-in-an-ionic-2-typescript-project/

4 Comments

  1. sumit solanki October 24, 2017
  2. SALVATORE MILITELLO November 1, 2016
  3. SALVATORE MILITELLO September 22, 2016
    • Lucas Jellema September 28, 2016