Angular 2:将外部 js 文件导入到组件中

IT技术 javascript angular webpack
2021-01-22 18:28:22

我要将这个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无法找到。

所以,

  1. 将外部js文件导入angular2的正确步骤是什么?
  2. 因为我使用的是 webpack,所以可以在 webpack 中实现吗?我参考了这个问题,由于无法解决,那里的 webpack 解决方案对我不起作用.ensure
6个回答

理想情况下,您需要有.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
    }
}

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

declare var drawGauge: any;

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

///<reference path="../path/to/d3gauage.d.ts"/>
谢谢。还有一个问题,在declare var drawGauge: any;转译这个 ts 文件时,什么时候会被引用?或者,换句话说,当 new drawGauge(this.opt),编译器如何知道drawGauge()实际上是在d3gauge.js
2021-03-13 18:28:22
我得到了ReferenceError: drawGauge is not defined是因为我在使用 webpack 吗?
2021-03-16 18:28:22
是的,在转译时,它必须知道有/或将有名为d3gauge. 在第二个问题中,它没有d3gauge.js将它分配给 中的一个global变量dom,即在运行时调用它的地方。
2021-03-23 18:28:22
@BingLu 嘿,伙计,您找到适合您的解决方案了吗?我仍然听说EXCEPTION: Uncaught (in promise): Error: Error in someComponent声明的变量is not defined到目前为止找不到解决方案。
2021-03-24 18:28:22
只需放入<script src="../../../../js/d3gauge.js"></script>index.html唯一的,没有其他地方,webpack 解决方案可能因为错误的路径而不起作用,但我对webpack
2021-04-02 18:28:22

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

这是一个普遍的答案。假设您想将一个名为 testjs.js 的文件导入到您的 angular 2 组件中。在您的资产文件夹中创建 testjs.js:

资产 > testjs.js

function test(){
    alert('TestingFunction')
}

在 index.html 中包含 testjs.js

索引.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>

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

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();
  }
}

最后在您的app.component.html 中测试该功能

应用程序组件.html

<h1>
  <button (click)='f()'>Test</button>
</h1>
我们需要在组件上声明函数名称吗,如果我有很多函数,我需要声明所有函数吗?它也不起作用我收到这些错误“错误参考错误:未定义测试”和“拒绝从 ' localhost:4200/assets/custom.js '执行脚本,因为它的 MIME 类型('text/html')不可执行,并启用了严格的 MIME 类型检查。”
2021-03-16 18:28:22

您可以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;

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

declare 不是 Declare
2021-03-13 18:28:22
嗨,你能告诉我把“声明常量测试:任何”部分放在哪里吗?? 组件内部?我试图把它放在导出类中,也在“导出类....”之前,但它没有用。
2021-03-27 18:28:22
在您的 app.component.ts 或任何要调用 Test 方法的 component.ts 文件中,只需在导入该组件的其他依赖项的顶部添加“Declare const Test:any”即可。
2021-03-31 18:28:22

以下方法适用于 Angular 5 CLI。

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

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

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

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

<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>

然后我在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);
    });
 }

}

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

<div id="gaugeBox"></div>

等等!:)

在此处输入图片说明

这是我在我的项目中做到的一种简单方法。

假设您需要使用,clipboard.min.js 并且为了示例起见,假设内部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>

app.component.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
    }

}