How to add External javascript library in Ionic2 Application

I am having a pure javascript library which is neither available in npm nor in any public repository.
Its a pure javascript file with extension .js. It has some functions which i need to use in my Ionic2 application.
How can i import such files in my Ionic2 Application.
Any references will be much appreciated.

You can try adding a <script> tag to index.html, but how easy it will be to integrate depends greatly on how the library is written.

@rhuldip For these kind of files, in my case I’ve put them inside /src/assets/js/, because they will be copied to the /www/assets/js/ folder, then I reference it in index.html and declare it (you can declare in declarations.d.ts).

For example, lets say you have a file named my-library.min.js that is accessed through the MyLibrary global variable (that is, window.MyLibrary). Then:

1) Put my-library.min.js inside /src/assets/js/ (if the folder /src/assets/ doesn’t have a sub-folder /js, just create it).

2) In /src/index.html include the script tag:

<script src="assets/js/my-library.min.js"></script>

3) In /src/declarations.d.ts include:

declare var MyLibrary: any;

4) Use it:

export class MyApp implements OnInit {

	public ngOnInit() {
		console.log('MyLibrary', MyLibrary);
		MyLibrary.doSomething();
	}
	
}
3 Likes

Thank you @lucasbasquerotto, its working well and good.

If the declarations.d.ts not exist, how can i declare de global variable?

@Hanzo You can just create a .d.ts file in your project. The declaration should be recognized. You could also declare it directly in your .ts file (if you are using it only there, I see no problem).

If when importing the library it returns an error like:

Error: Cannot find module “three” at webpackMissingModule…

Which would be the problem?

That’s an issue specific to Three, as we discussed yesterday. Three’s namespace is corrupted, so you have to do fancy webpack configuaration to use the non-core pieces of it, and even so, it doesn’t work well. If you follow the instructions in the issue I pointed you to yesterday, that’s the best option. But it really looks as though Three is unsupported, and the non-core features should be considered at or near end-of-life.

I too have a problem similar to this and I am getting an error something like this:

ERROR TypeError: jquery__WEBPACK_IMPORTED_MODULE_2__(...).gauge is not a function

How do I resolve this?