0

In angular and ionic, when I insert a library (in a script tag) in the index.html file, then do I also have to import it into a component to be able to use it? If so, why? By entering the script in index.html does the library not already have global visibility? What does this statement "declare var libr_name: any" mean?

Thanks

DaggeJ
  • 1,581
  • 7
  • 18
  • Even better: https://stackoverflow.com/questions/38855891/angular-cli-webpack-how-to-add-or-bundle-external-js-files – msanford Sep 05 '19 at 12:51

1 Answers1

0

You are absolutely right that after you add some library in the <script> tag it becomes visible globally.

But since you use typescript with angular, you need to declare a variable representing this library entry point. The reason is the typescript transpiller which has no idea about the fact you have added some libraries or any global variables.

By this line: declare var libr_name: any you actually make transpiller to stop throwing an error during the build, because now libr_name becomes a known variable.

If you face with such situation multiple times in your project, it probably would be nice to create separate globals.ts file where you declare all global variables and reexport them. Then in other files you need to import globals.ts.

globals.ts

declare var libr_name: any
declare var another_lib: any

export const globals = {
 libr_name,
 another_lib
}

any of your components .ts file

import {globals} from 'globals.ts'

// .... components code or whatever
globals.libr_name.do_stuff();
//....
Artem Arkhipov
  • 5,138
  • 5
  • 25
  • 44
  • Thanks, therefore with this statement: "declare var libr_name: any" , am I declaring a variable named "libr_name" that represents the entry point of the library, inside the component? – itbestdevelopment Sep 05 '19 at 12:53
  • @itbestdevelopment no, you actually notify typescript transpiller about existing one. You should know the name of global variable which that library creates. – Artem Arkhipov Sep 05 '19 at 12:59