How Import JS File in angular 6?

26,966

Solution 1

Angular 6 has a dedicated place to declare js files within the dedicated arrays of your angular.json, under

 /projects/$(youProjectName)/architect/build/options/scripts[]

and

 /projects/$(youProjectName)/architect/test/options/scripts[]

As an example:

npm install fast-levenshtein --save

will install a js library under node-modules

The path relative to the project of the js lib file is declared like this:

"scripts": [
   "node_modules/fast-levenshtein/levenshtein.js"
]

Then declare in your component the variable(s) to use, either as described by the npm documentation or by @LuaXD

Solution 2

You should include on index.html, e.g:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
   <title>A random project</title>
   <base href="/">

   <meta name="viewport" content="width=device-width, initial- 
    scale=1">
   <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
   <link rel="stylesheet" href="https://cartodb- 
  libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" 
/>
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.core.js"></script>

<app-root></app-root>
</body>
</html>

On this case I included cartodb.js library, then for use cartodb.js on any component, or service I use:

declare var cartodb: any;

At the beginning of any file (Component, Service, etc).

Note change cartodb by the name of the library you will use, for example for jquery is:

declare var jquery:any;
declare var $ :any;

You should have something like this:

import { Injectable } from '@angular/core';
// Other imports...

declare var cartodb: any;
@Injectable()
export class ARandomService {
}

P.s Search if the code you want to use doesn't exist in npm.

Share:
26,966
George
Author by

George

Updated on September 24, 2020

Comments

  • George
    George over 3 years

    how can I import a js file in angular 6. I tried to implement a navbar and it contains js functions. thanks!!!

    I Add my js file called nav.js

     "scripts": [
              "src/assets/js/nav.js"
            ]
    
  • gauti
    gauti over 5 years
    instead of using declare var, can't we import the files?
  • Sayed Mohd Ali
    Sayed Mohd Ali over 5 years
    declare var cartodb: any; declare var jquery:any; declare var jquery-ui:any; I can import multiple libraries like that in my TypeScript?
  • juniortan
    juniortan over 3 years
    what if it's a custom js file. how do i declare the variables