Angular2:将外部js文件导入组件

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


import '../../../../js/d3gauge.js';

export class MemMonComponent {

    createMemGauge() {

        new drawGauge(this.opt);  //drawGauge() is a function inside d3gauge.js

    }

}

然后在相应的模板文件中添加


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

但这是行不通的,drawGauge无法找到。


所以,


将外部js文件导入angular2的正确步骤是什么?

由于我使用的是webpack,是否可以在webpack中进行?我指的是这个问题,由于无法解决,因此webpack解决方案对我不起作用.ensure。


慕村225694
浏览 1341回答 3
3回答

动漫人物

理想情况下,您需要具有.d.ts键入文件才能Linting正常工作。但是似乎d3gauge没有,您可以要求开发人员提供并希望他们会听。或者,您可以通过执行以下操作解决此特定问题declare var drawGauge: any;import '../../../../js/d3gauge.js';export class MemMonComponent {&nbsp; &nbsp; createMemGauge() {&nbsp; &nbsp; &nbsp; &nbsp; new drawGauge(this.opt);&nbsp; //drawGauge() is a function inside d3gauge.js&nbsp; &nbsp; }}如果您在多个文件中使用它,则可以d3gauage.d.ts使用以下内容创建文件declare var drawGauge: any;并boot.ts在顶部的(bootstrap)文件中引用它,就像这样///<reference path="../path/to/d3gauage.d.ts"/>

喵喔喔

在浪费大量时间寻找解决方案之后,我找到了一个。为了方便起见,我使用了完整的代码,可以用它替换整个文件。这是一个普遍的答案。假设您要将名为testjs.js的文件导入您的angular 2组件。在您的资产文件夹中创建testjs.js:资产> testjs.jsfunction test(){&nbsp; &nbsp; alert('TestingFunction')}在您的index.html中包含testjs.jsindex.html<!doctype html><html><head>&nbsp; <meta charset="utf-8">&nbsp; <title>Project1</title>&nbsp; <base href="/">&nbsp; <meta name="viewport" content="width=device-width, initial-scale=1">&nbsp; <link rel="icon" type="image/x-icon" href="favicon.ico">&nbsp; <script src="./assets/testjs.js"></script></head><body>&nbsp; <app-root>Loading...</app-root></body></html>在您要调用此js的app.component.ts或任何component.ts文件中,声明一个变量并调用如下函数:app.component.tsimport { Component } from '@angular/core';declare var test: any;@Component({&nbsp; selector: 'app-root',&nbsp; templateUrl: './app.component.html',&nbsp; styleUrls: ['./app.component.css']})export class AppComponent {&nbsp; title = 'app works!';&nbsp; f(){&nbsp; &nbsp; new test();&nbsp; }}最后在您的app.component.html中测试功能app.component.html<h1>&nbsp; <button (click)='f()'>Test</button></h1>

小怪兽爱吃肉

您可以在文件中包含js扩展名,而不必在中添加文件扩展名。index.html.angular-cli-json这些是我执行此步骤的步骤:首先将您的外部js文件包含在assets/js在.angular-cli.json-在脚本下添加文件路径: [../app/assets/js/test.js]在要使用js文件功能的组件中。在顶部将文件导入为声明declare const Test:any;之后,您可以访问其功能,例如 Test.add()
打开App,查看更多内容
随时随地看视频慕课网APP