【问题标题】:Using Node module with out type defination in Angular 2在Angular 2中使用没有类型定义的Node模块
【发布时间】:2017-08-14 01:22:13
【问题描述】:

我编写了一个非常简单的节点模块 [ npm install twinconsole ] 并发布到 npm。

我还包括浏览器build(umd 模块),以便它可以 也可以在浏览器中使用。

以下是node模块相关代码

module.exports.print = msg => {
console.log(msg);
}

现在我想使用我的 Angular 2 typescript 应用程序中的这个节点模块来做到这一点

  1. 我已在 index.html 中包含以下 CDN 文件。

我需要做什么才能在节点模块中导出的 print() 函数可以在下面的根组件中使用

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

declare var twinconsole: any;  // ADDEED THIS LINE , IS THIS CORRECT ?


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

  title = 'app works!';
}

【问题讨论】:

  • 是的,您的声明语句应该可以正常工作。我已经对 CryptoJS 进行了类似的加密声明。如果它们的 API 更广泛,我发现为声明的变量创建一个接口很有用。这允许像 VSCode 这样的编辑器仍然提供良好的开发体验,因为它们通过自动完成公开界面。

标签: node.js angular typescript node-modules


【解决方案1】:
import { Component } from '@angular/core';

//define interface to get "intellisense" aka autocomplete and type errors
interface TwinConsole{
  print(msg:string);
}

declare var twinconsole: TwinConsole;


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

  title = 'app works!';
}

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2017-02-20
    • 2016-06-28
    • 2017-03-06
    • 2018-07-13
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多