Pregunta

So I'm trying to write a very basic module that I can use in node. It is producing an instantiation error that I'm not quite sure how to solve. Please forgive the naming, I'm just hacking this example together in order to get my head around the problem.

The module in use:

module Server {
  export interface iCalc {
    add(x : number, y : number) : number;
    mul(x : number, y : number) : number;
    div(x : number, y : number) : number;
    sub(x : number, y : number) : number;
  }

  export class ServerCalc implements iCalc {
    constructor() {}
    add( x : number, y : number) {
      return x + y;
    }
    mul( x : number, y : number) {
      return x * y;
    }
    div( x : number, y : number) {
      return x/y;
    }
    sub( x : number, y : number) {
      return x-y;
    }
  }
}

The very basic test-bed:

/// <reference path='node.d.ts' />
/// <reference path='Server.ts' />
var serve = require("./Server.js");


var tmp = new serve.ServerCalc();
console.log(tmp.add(1,1));

Note I've used the above method to try and make the object reachable by node. I've also tried the below, following what should be a more TypeScript idiomatic approach (but it produces the same error):

/// <reference path='Server.ts' />


var tmp = new Server.ServerCalc();
console.log(tmp.add(1,1));

And the error it produces:

.../test.js:5
var tmp = new serve.ServerCalc();
      ^
      TypeError: undefined is not a function
      at Object.<anonymous> (.../test.js:5:11)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Function.Module.runMain (module.js:497:10)
  at startup (node.js:119:16)
  at node.js:901:3

The module is being compiled with the --module commonjs option.

¿Fue útil?

Solución

First off don't use internal modules with node. These are redundant. I.e. Remove "module Server"

Second the ".js" part is invalid even for plain js so it should have been,

var serve = require("./Server");

Thirdly typescript uses export/import combo for external modules:

import serve = require("./Server");

PS : this video might help you understand more http://www.youtube.com/watch?hd=1&v=KDrWLMUY0R0

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top