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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37081943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:53:00  来源:igfitidea点击:

Angular 2: import external js file into component

javascriptangularwebpack

提问by Bing Lu

I'm going to import this d3gauge.jsfile into one of my angular2 component, memmon.component.tsfile.

我要将这个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
    }
}

and in the corresponding template file, add

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

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

But it doesn't work, drawGaugecan't be found.

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

So,

所以,

  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 .ensurecan't be resolved.
  1. 将外部js文件导入angular2的正确步骤是什么?
  2. 因为我使用的是 webpack,所以可以在 webpack 中实现吗?我参考了这个问题,由于无法解决,那里的 webpack 解决方案对我不起作用.ensure

回答by Ankit Singh

Ideally you need to have .d.tsfile for typings to let Lintingwork.

理想情况下,您需要有.d.ts用于打字的文件才能Linting工作。

But It seems that d3gaugedoesn't have one, you can Ask the developers to provide and hope they will listen.

不过好像d3gauge没有,你可以请开发者提供,希望他们听听。



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
    }
}


If you use it in multiple files, you can create a d3gauage.d.tsfile with the content below

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

declare var drawGauge: any;

and reference it in your boot.ts(bootstrap) file at the top, like this

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

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

回答by Muhammad Rehan Qadri

After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.

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

This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:

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

assets > testjs.js

资产 > testjs.js

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

include testjs.js in your index.html

在 index.html 中包含 testjs.js

index.html

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

In your app.component.ts or in any component.ts file where you want to call this js declare a variable and call the function like below:

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

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

Finally in your app.component.htmltest the function

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

app.component.html

应用程序组件.html

<h1>
  <button (click)='f()'>Test</button>
</h1>

回答by Sitaram

Instead of including your jsfile extension in index.html, you can include it in .angular-cli-jsonfile.

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

These are the steps I followed to get this working:

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

  1. First include your external jsfile in assets/js
  2. In .angular-cli.json- add the file path under scripts: [../app/assets/js/test.js]
  3. In the component where you want to use the functions of the jsfile.
  1. 首先包含您的外部js文件assets/js
  2. .angular-cli.json- 在脚本下添加文件路径: [../app/assets/js/test.js]
  3. 在要使用js文件功能的组件中。

Declare at the top where you want to import the files as

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

declare const Test:any;

After this you can access its functions as for example Test.add()

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

回答by PeteZaria

The following approach worked in Angular 5 CLI.

以下方法适用于 Angular 5 CLI。

For sake of simplicity, I used similar d3gauge.js demo created and provided by oliverbinns - which you may easily find on Github.

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

So first, I simply created a new folder named externalJSon same level as the assetsfolder. I then copied the 2 following .js files.

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

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

I then made sure to declare both linked directives in main index.html

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

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

I then added a similar code in a gauge.component.tscomponent as followed:

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

}

}

and finally, I simply added a div in corresponding gauge.component.html

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

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

et voilà ! :)

等等!:)

enter image description here

在此处输入图片说明

回答by jonathana

Here is a simple way i did it in my project.

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

lets say you need to use clipboard.min.jsand for the sake of the example lets say that inside clipboard.min.jsthere is a function that called test2().

假设您需要使用,clipboard.min.js并且为了示例,假设内部clipboard.min.js有一个名为test2().

in order to use test2() function you need:

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

  1. make a reference to the .js file inside you index.html.
  2. import clipboard.min.jsto your component.
  3. declare a variable that will use you to call the function.
  1. 引用 index.html 中的 .js 文件。
  2. 导入clipboard.min.js到您的组件中。
  3. 声明一个将使用您调用函数的变量。

here are only the relevant parts from my project (see the comments):

这里只是我项目中的相关部分(见评论):

index.html:

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

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
    }

}

回答by Kamil Kie?czewski

You can also try this:

你也可以试试这个:

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

and just new drawGauge(this.opt);in your ts-code. This solution works in project with angular-cli embedded into laravel on which I currently working on. In my case I try to import poliglotlibrary (btw: very good for translations) from node_modules:

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

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

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

This solution is good because i don't need to COPYany files from node_modules:) .

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

UPDATE

更新

You can also look on this LISTof ways how to include libs in angular.

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

回答by Sukhdevsinh Jadeja

1) First Insert JS file path in an index.htmlfile :

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

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

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

2) Import JS file and declare the variable in component.ts:

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

  • import './../../../assets/video.js';
  • declare var RunPlayer: any;

    NOTE:Variable name should be same as the name of a function in js file

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

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

3) Call the js method in the component

3)调用组件中的js方法

ngAfterViewInit(){

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

}

回答by Anuj Vohra

Let's say you have added a file "xyz.js" under assets/jsfolder in some Angularproject in Visual-Studio, then the easiest way to include that file is to add it to .angular-cli.json

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

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

You should be able to use this JS file's functionality in your component or .ts files.

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

回答by noamyg

For .jsfiles that expose more than one variable (unlike drawGauge), a better solution would be to set the Typescript compiler to process .jsfiles.

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

In your tsconfig.json, set allowJsoption to true:

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

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

Otherwise, you'll have to declare each and every variable in either your component.tsor d.ts.

否则,您必须在您的component.tsd.ts.