3

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 3

2

You can use system.js to import file at runtime as below, you have to add systemjs in node_modules.

System.import("src/assets/js/file.js").then(fileInstance => {
      console.log(fileInstance);
});
Sign up to request clarification or add additional context in comments.

Comments

1

In component.ts you should declare the name of the function you want to use.

declare let encode:any 

ngOnInit(){
  encode()
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.