网站搜索

node.js - NodeJS、TypeScript 和 typescript-collections


我正在尝试在 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 集合库替代……

答案#1

你有一个内部模块与外部模块的问题。

TypeScript 集合库被编写为一个内部模块——一个标准的 JavaScript 文件,你可以直接将其放入网页中的script标签中。

然而,Node 的 require 期望的是一个与 CommonJS 兼容的文件,该文件会将某些内容分配给 exports,换句话说,就是一个 外部模块。发生的情况是,node.js 找到 collections.js,执行它,并返回执行该文件时的 exports 对象。因为它只是一个普通的 JS 文件,所以导出的对象是 {} —— 空的。

最好的解决方法是:

  1. 将你对 collections.ts 的引用替换为 collections.d.ts,只是为了正确性(运行 tsc --d collection.ts 来生成此文件)
  2. 在 Node 中使用一些方法来加载“纯”JS文件。一个不错的一行方法(来自链接的问题)是 eval(require('fs').readFileSync('./path/to/file.js', 'utf8'));