171

I have a JavaScript file called abc.js that has a 'public' function called xyz(). I want to call that function in my Angular project. How do I do that?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Piyush Jain
  • 1,781
  • 2
  • 10
  • 13

8 Answers8

137

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';
Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • 10
    i added path in scripts as "scripts": [ "./assets/common_header_sidebar.js" ]; then in typing.d.ts i wrote declare var commonHeader:any; and then in my ts file i wrote import * as commonHeaderModule from 'commonHeader'; but getting "Cannot find module 'commonHeader'." error – Piyush Jain Jun 29 '17 at 06:14
  • `commonHeader` must be the name of the object exported in the javascript file – Aravind Jun 29 '17 at 06:25
  • yes commonHeader is the function name that i have to export from the js file – Piyush Jain Jun 29 '17 at 06:28
  • 14
    i might sound silly for asking this. but how the file name in the path(declared in angular-cli.json) and declaring name of the object in typing.d.ts file is related. since i am importing from the name of the declared object not the file – Piyush Jain Jun 29 '17 at 06:39
  • 2
    can you create a `plunker` to reproduce – Aravind Jun 29 '17 at 06:40
  • will uploading the js file do the job ?? since i haven't created any plunker till now . so might take time in that – Piyush Jain Jun 29 '17 at 06:48
  • 4
    done with the integration it is just that i had to declare the function in my ts file where i was using it and import was not required. Thanks a ton . – Piyush Jain Jun 29 '17 at 07:05
  • Can I use online link in the script tag? Is there any way to use online **JS** file link to use in application? – Habib Oct 13 '17 at 07:48
  • you can use the script reference too – Aravind Oct 13 '17 at 10:56
  • @Ameya I didn''t understand your question – Aravind Apr 23 '18 at 12:01
  • We don't have to import once again if we declare the variable in typing.d.ts – Sudhir Sapkal Jul 17 '18 at 07:00
  • I could see plugin name in chrome console, but unable to import in ts file. – gauti Nov 19 '18 at 11:18
  • 1
    I don't have 'typings.d.ts' file in my project, so what should I do? – Habib Nov 27 '18 at 08:27
  • 2
    @Aravind what if I don't have typing.d.ts file in my Angular 4 project? – Habib Dec 03 '18 at 07:11
  • @HabibM.Farooq can you please share me your code and the steps you tried or try creating a new post if it is completely different from this post – Aravind Dec 03 '18 at 07:49
  • 1
    @Aravind well I was trying to add a js file and when I search for a typing.d.ts file I didn't find any. I create my project from Angular CLI "ng new appname" by this method. And everything is working fine but there is no typings.d.ts file in my project. Do I have to create it by myself or is it some problem or some error? – Habib Dec 03 '18 at 07:53
  • @ HabibM.Farooq you must create this file – PuntanetDeveloper Dec 13 '18 at 11:09
  • 1
    FYI angular-cli.json has been renamed to angular.json from angular 6+ – Howdy Aug 08 '19 at 19:16
  • Add a `typings.d.ts` file in your `src` folder if it does not already exist. – Ollie May 03 '20 at 04:36
  • 2
    Still has an error when trying to import it : "Cannot find module 'myVariableName' or its corresponding type declarations." – Neyt Mar 30 '22 at 13:06
  • How can this work? Doesn't work for me,.. How is your import linked to the script? – Yannick Mussche Jun 27 '23 at 18:29
48

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
48

Add external js file in index.html.

<script src="./assets/vendors/myjs.js"></script>

Here's myjs.js file :

var myExtObject = (function() {

    return {
      func1: function() {
        alert('function 1 called');
      },
      func2: function() {
        alert('function 2 called');
      }
    }

})(myExtObject||{})


var webGlObject = (function() { 
    return { 
      init: function() { 
        alert('webGlObject initialized');
      } 
    } 
})(webGlObject||{})

Then declare it is in component like below

demo.component.ts

declare var myExtObject: any;
declare var webGlObject: any;

constructor(){
    webGlObject.init();
}

callFunction1() {
    myExtObject.func1();
}

callFunction2() {
    myExtObject.func2();
}

demo.component.html

<div>
    <p>click below buttons for function call</p>
    <button (click)="callFunction1()">Call Function 1</button>
    <button (click)="callFunction2()">Call Function 2</button>
</div>

It's working for me...

barbsan
  • 3,418
  • 11
  • 21
  • 28
Nagnath Mungade
  • 921
  • 10
  • 11
  • 4
    Very thorough example thanks, it worked for me on angular 6. None of the other answers worked. – Daniel Filipe Dec 10 '19 at 23:08
  • 2
    Fwiw, [here are some explanations of what `declare` does](https://stackoverflow.com/q/35019987/1028230) -- essentially "_`declare` is used to tell TypeScript that the variable has been created elsewhere_" (from [this answer](https://stackoverflow.com/a/35020317/1028230)). – ruffin May 13 '20 at 15:29
  • 1
    I think the index.html file is empty by design and I think you should keep it that way. The ng serve should take care of all javascript files. – Herman Van Der Blom Aug 25 '20 at 13:38
19

You can either

import * as abc from './abc';
abc.xyz();

or

import { xyz } from './abc';
xyz()
crash
  • 4,152
  • 6
  • 33
  • 54
  • 33
    what am i supposed to do when the file is hosted somewhere but not in the local repo? – Piyush Jain Jun 29 '17 at 06:06
  • did you figure this out? – Luis Aceituno Feb 22 '18 at 16:30
  • 1
    Getting errors in both methods. Well I have a .js file in my project but when I import by first method its give me error in compiling and can't find any module when I use the second method. And I am just using slick slider. – Habib Nov 27 '18 at 08:30
3

I resolved this issue by adding "allowJs": true within "compilerOptions" in tsconfig.json file!

Aakash Goplani
  • 1,150
  • 1
  • 19
  • 36
3

- Let us assume our script file custom.js looks like this: -

var utilObj = {
    dummyFunc: () => {
        console.log('Calling dummy function!');
    }
}

- Add your javascript/script file in scripts array in angular.json file.

"scripts": [
    "src/custom.js" 
 ],

Should look like this: -

enter image description here

- Add below code snippet in typings.d.ts. If this file doesn't exist, create one in src folder.

declare var utilObj:any;

Keep your variable name similar to property of script file. Here utilObj is the property name.

- Now, You can consume this script/js file directly in your component or .ts file.

You need not import the file in component file or .ts file now as we have given the typing defination for the script file already in typings.d.ts file.

Example: -

ngOnInit() {
  console.log('Starting Application!');
  utilObj.dummyFunc();
}

- Output: -

enter image description here

d1fficult
  • 931
  • 8
  • 18
0

This might sound silly, but if you feel that you are properly exporting your JavaScript helper function utils/javaScriptHelperFunction.js

export function javaScriptFunction() {
   // DO HELPER FUNCTION STUFF
}

If you have done your checks as mentioned in the above answers, just close and open your code editor...start with the quick basic troubleshooting before going down the rabbit hole.

tony2tones
  • 1,422
  • 1
  • 18
  • 19
-2

You can create a function in the js file which includes the function you are trying to obtain:

For example: I did a Todo-List in JS and wanted to use in my angular app.

[TODO.JS]:

enter image description here

Next we have to import in the component.ts where we want to use our function:

ExampleComponent.ts The links are the photos of the different parts of the code.

[example.component.ts]:

enter image description here

desertnaut
  • 57,590
  • 26
  • 140
  • 166