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

Bin*_* Lu 56 javascript webpack angular

我要将这个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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<script src="../../../../js/d3gauge.js"></script>
Run Code Online (Sandbox Code Playgroud)

但它不起作用,drawGauge无法找到.

所以,

  1. 将外部js文件导入angular2的正确步骤是什么?
  2. 因为我正在使用webpack,是否可以在webpack中进行?我指的是这个问题,webpack解决方案对我来说.ensure无法解决,因为无法解决.

Ank*_*ngh 66

理想情况下,你需要有.d.ts文件的打字Linting工作.

但似乎d3gauge没有一个,你可以要求开发者提供并希望他们会倾听.


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

declare var drawGauge: any;

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

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

declare var drawGauge: any;
Run Code Online (Sandbox Code Playgroud)

boot.ts在顶部的(引导程序)文件中引用它,就像这样

///<reference path="../path/to/d3gauage.d.ts"/>
Run Code Online (Sandbox Code Playgroud)


Muh*_*dri 45

在浪费了大量时间寻找解决方案之后,我找到了一个.为方便起见,我使用了可以替换整个文件的完整代码.

这是一般答案.假设您要将名为testjs.js的文件导入角度2组件.在assets文件夹中创建testjs.js:

assets> testjs.js

function test(){
    alert('TestingFunction')
}
Run Code Online (Sandbox Code Playgroud)

在index.html中包含testjs.js

的index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Project1</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <script src="./assets/testjs.js"></script>

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在你的app.component.ts或你要调用的任何component.ts文件中,这个js声明一个变量并调用如下函数:

app.component.ts

import { Component } from '@angular/core';

declare var test: any;


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app works!';


  f(){
    new test();
  }
}
Run Code Online (Sandbox Code Playgroud)

最后在app.component.html中测试该函数

app.component.html

<h1>
  <button (click)='f()'>Test</button>
</h1>
Run Code Online (Sandbox Code Playgroud)

  • 这是我正在寻找的答案.非常感谢,你能在这里分享为什么我们需要'新'吗? (4认同)

Sit*_*ram 10

您可以在文件中包含,而不是包含js文件扩展名.index.html.angular-cli-json

这些是我为实现这一目标而采取的步骤.

  1. 首先包括您的外部js文件assets/js
  2. .angular-cli.json- 添加脚本下的文件路径: [../app/assets/js/test.js]
  3. 在要使用js文件功能的组件中.

在您要导入文件的顶部声明为

declare const Test:any;
Run Code Online (Sandbox Code Playgroud)

在此之后,您可以访问其功能,例如 Test.add()


Pet*_*ria 5

以下方法在Angular 5 CLI中有效。

为了简单起见,我使用了由Oliverbinns创建和提供的类似d3gauge.js演示-您可以在Github上轻松找到它。

因此,首先,我只是在与资产文件夹相同的级别上创建了一个名为externalJS的新文件夹。然后,我复制了以下2个.js文件。

  • d3.v3.min.js
  • d3gauge.js

然后,我确保在main index.html中声明两个链接的指令

<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>
Run Code Online (Sandbox Code Playgroud)

然后,我在gauge.component.ts组件中添加了类似的代码,如下所示:

import { Component, OnInit } from '@angular/core';

declare var d3gauge:any; <----- !
declare var drawGauge: any; <-----!

@Component({
  selector: 'app-gauge',
  templateUrl: './gauge.component.html'
})

export class GaugeComponent implements OnInit {
   constructor() { }

   ngOnInit() {
      this.createD3Gauge();
   }

   createD3Gauge() { 
      let gauges = []
      document.addEventListener("DOMContentLoaded", function (event) {      
      let opt = {
         gaugeRadius: 160,
         minVal: 0,
         maxVal: 100,
         needleVal: Math.round(30),
         tickSpaceMinVal: 1,
         tickSpaceMajVal: 10,
         divID: "gaugeBox",
         gaugeUnits: "%"
    } 

    gauges[0] = new drawGauge(opt);
    });
 }
Run Code Online (Sandbox Code Playgroud)

}

最后,我只是在相应的gauge.component.html中添加了一个div

<div id="gaugeBox"></div>
Run Code Online (Sandbox Code Playgroud)

等!:)

在此处输入图片说明


jon*_*ana 5

这是我在项目中完成的一个简单方法。

假设您需要使用clipboard.min.js and ,为了举例说明,假设内部clipboard.min.js有一个名为 的函数test2()

为了使用 test2() 函数,您需要:

  1. 引用index.html 中的.js 文件。
  2. 导入clipboard.min.js到您的组件中。
  3. 声明一个将使用您来调用该函数的变量。

这里只是我的项目的相关部分(请参阅评论):

索引.html:

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>


    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>

    <!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
    <script src="app/txtzone/clipboard.min.js"></script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

应用程序组件.ts:

import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],
})



export class TxtZoneComponent implements AfterViewInit {

    // call test2
    callTest2()
    {   
        new test2(); // the javascript function will execute
    }

}
Run Code Online (Sandbox Code Playgroud)