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

查看:34
本文介绍了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.

所以,

  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天全站免登陆