How to add External javascript library in Ionic2 Application


#1

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.


#2

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.


#3

@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();
	}
	
}

Adding a pure JS library to Ionic using NPM
#4

Thank you @lucasbasquerotto, its working well and good.


#5

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


#6

@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).


#7

If when importing the library it returns an error like:

Error: Cannot find module “three” at webpackMissingModule…

Which would be the problem?


#8

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.