Import external js File in Angular 4 and access functions and variables

Viewed 7202

Maybe my title is a bit unclear, so I will try to explain my problem with a simple task.

Lets say I have a the following Javascript File "file.js":

var number = 4;

function encode(){
  console.log("encode in "file.js" has been called...");
} 

I place this script in my angular4 project in "src/assets/js/file.js".

In ".angular-cli.json" I add the path of the script

"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "./assets/js/modernizr.js",
  "./assets/js/webflow.js",
  "./assets/js/file.js"

Now my question is how can import or use this script file in my app.module.ts or any other component, without adding it to index.html

I tried several ways:

import * as test from 'assets/js/file.js';
import {test} from 'assets/js/file.js';
declare var file: any;

Unfortunately, none worked...

I would really appreciated it, if you guys could help me out.

3 Answers

You can Import js locally to ts file like this : import '../../../scripts/custom.js';

then declare method name in custom.js that you want to use like this declare var fAlert; then in a place like ngOnInit directly use this method

fAlert();

Related