【问题标题】:How can I use a js library as a module in my angular 4.x projects?如何在我的 Angular 4.x 项目中使用 js 库作为模块?
【发布时间】:2019-02-01 14:43:23
【问题描述】:

例如这是我的 test.js 文件:

function test() { console.log('Test is working!'); };

这是我旁边的 test.d.ts 文件:

declare module 'test' {
export function test(): void;
};

但是当我尝试像这样在我的 app.component.ts 中使用这个模块时:

import {Component, OnInit} from '@angular/core';
import * as Test from 'test';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
 title = 'app';
 a = Test;

 ngOnInit() {
  this.a.test();
 }
}

我会看到找不到模块:错误:无法解析“测试”。 顺便说一下,这是我的 StackBlitz 的项目链接: Link of above project

【问题讨论】:

  • 尽可能创建一个 StackBlitz 项目。一般来说,如果您有第三方脚本,那么您首先必须将其添加到 angular.json.angular-cli.json 中的脚本数组中。然后,您必须在组件中声明一个变量,并从您尝试导入的库中导入 * 作为别名。这样就可以了。

标签: javascript angular typescript import module


【解决方案1】:

我会看到错误:找不到模块“测试”。

你有declare module 'test' {,但你导入Test(注意testTest的大小写差异)。

【讨论】:

  • 那是我在问题中的错误,正确的代码仍然不适合我
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多