最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Import external js File in Angular 4 and access functions and variables - Stack Overflow

programmeradmin2浏览0评论

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 ponent, 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.

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 ponent, 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.

Share Improve this question asked Jul 13, 2017 at 12:22 TurpalTurpal 1371 gold badge2 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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);
});

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

declare let encode:any 

ngOnInit(){
  encode()
}

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

发布评论

评论列表(0)

  1. 暂无评论