Angular 2:将外部js文件导入组件 [英] Angular 2: import external js file into component

查看:52
本文介绍了Angular 2:将外部js文件导入组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将此 d3gauge.js 文件导入到我的angular2组件之一memmon.component.ts文件中.

I'm going to import this d3gauge.js file into one of my angular2 component, memmon.component.ts file.

import '../../../../js/d3gauge.js';
export class MemMonComponent {
    createMemGauge() {
        new drawGauge(this.opt);  //drawGauge() is a function inside d3gauge.js
    }
}

并在相应的模板文件中添加

and in the corresponding template file, add

<script src="../../../../js/d3gauge.js"></script>

但是它不起作用,找不到drawGauge.

But it doesn't work, drawGaugecan't be found.

所以

  1. 将外部js文件导入angular2的正确步骤是什么?
  2. 由于我使用的是webpack,是否可以在webpack中使用它?我指的是问题,那里的webpack解决方案没有由于.ensure无法解决,因此无法为我工作.
  1. what're correct steps to import an external js file to angular2?
  2. since I'm using webpack, is it possible to do it in webpack? I refer to this question , the webpack solution there doesn't work for me as a result of .ensure can't be resolved.

推荐答案

理想情况下,您需要具有.d.ts文件才能进行键入,以使Linting正常工作.

Ideally you need to have .d.ts file for typings to let Linting work.

但是d3gauge似乎没有,您可以要求开发人员提供并希望他们会听.

But It seems that d3gauge doesn't have one, you can Ask the developers to provide and hope they will listen.

或者,您可以通过执行此操作来解决此特定问题

Alternatively, you can solve this specific issue by doing this

declare var drawGauge: any;

import '../../../../js/d3gauge.js';
export class MemMonComponent {
    createMemGauge() {
        new drawGauge(this.opt);  //drawGauge() is a function inside d3gauge.js
    }
}


如果在多个文件中使用它,则可以使用以下内容创建一个d3gauage.d.ts文件

declare var drawGauge: any;

并像这样在顶部的boot.ts(引导)文件中引用它

and reference it in your boot.ts (bootstrap) file at the top, like this

///<reference path="../path/to/d3gauage.d.ts"/>

这篇关于Angular 2:将外部js文件导入组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆