【问题标题】:NodeJS, TypeScript and typescript-collectionsNodeJS、TypeScript 和 typescript 集合
【发布时间】:2014-07-01 08:57:35
【问题描述】:

我正在尝试在 NodeJS 中使用来自 typescript-collections 的 Dictionary 类:

/// <reference path="../../../scripts/collections.ts" />
var collections = require('../../../scripts/collections');

export class AsyncProcessorCommand implements interfaces.IAsyncProcessorCommand
{
    public static Type = 'RabbitMon.AsyncProcessorCommand:RabbitMon';
    public GetType = () => 'RabbitMon.AsyncProcessorCommand:RabbitMon';

    public ID: string;

    constructor(public Action: string, public Arguments?: collections.Dictionary<string, string>) {
        this.ID = uuid.v4();

        this.Arguments = new collections.Dictionary<string, string>();
        //I've also tried the following
        //this.Arguments = new collections.Dictionary<string, string>((key: string) => sha1(key));
    }
}

但我在new Dictionary 上不断收到以下错误:

TypeError: undefined is not a function

有人知道这里发生了什么吗?我也非常乐意替换一个更好的工作 TS 集合库...

【问题讨论】:

    标签: node.js collections typescript


    【解决方案1】:

    你有一个internal vs external modules 问题。

    TypeScript Collections 库被编写为一个内部模块——一个标准的 JavaScript 文件,您可以将其放入网页中的 script 标记中。

    Node 的require,然而,期待一个CommonJS 兼容的文件,它将分配一些东西给exports,换句话说,一个外部模块。发生的事情是 node.js 找到 collections.js,执行它,并从评估文件中返回 exports 对象。因为只是一个普通的JS文件,所以导出的对象是{} -- 为空。

    最好的解决办法是:

    1. 为了正确起见,将您对collections.ts 的引用替换为collections.d.ts 的引用(运行tsc --d collection.ts 以生成此文件)
    2. 使用some solution 在节点中加载“vanilla”JS 文件。一个好的单线(来自链接的问题)是eval(require('fs').readFileSync('./path/to/file.js', 'utf8'));

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 1970-01-01
      • 2020-08-10
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      相关资源
      最近更新 更多