Pregunta

I'm trying to use the Dictionary class from from typescript-collections within NodeJS:

/// <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));
    }
}

But I keep getting the following error on the new Dictionary:

TypeError: undefined is not a function

Anyone know what's going on here? I'm also perfectly happy to substitute a better working TS collections library...

¿Fue útil?

Solución

You have a internal vs external modules problem.

The TypeScript Collections library is written as an internal module -- a standard JavaScript file that you could just throw in to a script tag in a webpage.

Node's require, however, is expecting an CommonJS-compatible file that will assign something to exports, in other words an external module. What's happening is that node.js finds collections.js, executes it, and returns you back the exports object from evaluating the file. Because it's just a regular JS file, the exported object is {} -- empty.

The best fix would be:

  1. Replace your reference to collections.ts with one to collections.d.ts, just for correctness's sake (run tsc --d collection.ts to generate this file)
  2. Use some solution for loading "vanilla" JS files in node. A good one-liner (from the linked question) is eval(require('fs').readFileSync('./path/to/file.js', 'utf8'));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top