繁体   English   中英

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

[英]Angular 2: import external js file into component

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

理想情况下,你需要有.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 (bootstrap) 文件中引用它,像这样

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

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

这是一个普遍的答案。 假设您想将一个名为 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>

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

这些是我为使其工作而遵循的步骤:

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

在顶部声明要将文件导入为

declare const Test:any;

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

以下方法适用于 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
    }

}

你也可以试试这个:

import * as drawGauge from '../../../../js/d3gauge.js';

new drawGauge(this.opt); 在您的 ts 代码中。 该解决方案适用于将 angular-cli 嵌入到我目前正在处理的 laravel 中的项目。 就我而言,我尝试从poliglot导入poliglot库(顺便说一句:非常适合翻译):

import * as Polyglot from '../../../node_modules/node-polyglot/build/polyglot.min.js';
...
export class Lang 
{
    constructor() {

        this.polyglot = new Polyglot({ locale: 'en' });
        ...
    }
    ...
}

这个解决方案很好,因为我不需要node_modules复制任何文件 :) 。

更新

您还可以查看如何在 angular 中包含库的方法列表

1) 首先在index.html文件中插入 JS 文件路径:

<script src="assets/video.js" type="text/javascript"></script>

2) 导入 JS 文件并在component.ts 中声明变量:

  • 导入'./../../../assets/video.js';
  • 声明 var RunPlayer : any;

    注意:变量名应与 js 文件中的函数名相同

3)调用组件中的js方法

ngAfterViewInit(){

    setTimeout(() => {
        new RunPlayer();
    });

}

假设您在Visual-Studio 的某个Angular项目中的assets/js文件夹下添加了一个文件“xyz.js”,那么包含该文件的最简单方法是将其添加到.angular-cli.json

"scripts": [ "assets/js/xyz.js" ],

您应该能够在您的组件或 .ts 文件中使用此 JS 文件的功能。

对于公开多个变量的.js文件(与drawGauge不同),更好的解决方案是设置 Typescript 编译器来处理.js文件。

在您的tsconfig.json ,将allowJs选项设置为 true:

"compilerOptions": {
     ...
    "allowJs": true,
     ...
}

否则,您必须在component.tsd.ts声明每个变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM