My nodejs Typescript server has grown in complexity and now relies on a few classes defined in another .ts file. This has created a strange compilation problem:
-
tsc server.tscompiles everything fine. Butnode server.jscrashes at
the first line that instantiates a class from the other .ts file -
tsc --out server.js server.tsresults in the error message: “module
emit collides with emitted script” -
tsc --out serv.js server.tsseems to work but actually compiles
everything EXCEPT server.ts. The code from the other files is there andnode serv.jsjust returns without any output
I’m not the only one with this error, https://typescript.codeplex.com/workitem/294 unfortunately the solution on codeplex doesn’t work for me.
How do I use tsc correctly ?
Your
server.tsdependencies need to be modules that export their surface area with top-levelexportdirectives, andserver.tsshould load them usingimportdirectives. The root cause here is that TypeScript has two different sorts of universes for compilation.The first is the default one that you’d use for regular webpages, where some simple loader takes 1 or more source files in some fixed order and executes them in that order, and you’re on your own for dependency ordering. This is called “program” compilation. In program compilation, you might do side-by-side compilation (a.ts => a.js, b.ts => b.js), or you might do concatenated compilation using
--out((a.ts + b.ts) => out.js).In program compilation, you refer to your references using
///<reference>tags. If those references are to source files (.ts), they’ll get concatenated in to the output if using--out, or emitted as a side-by-side.jsfile otherwise. If those references are to a declaration file (.d.ts), you’re basically saying you will be getting definitions for those files loaded via the external loader (i.e. a<script>tag in the browser).The second is the kind of compilation you’d use for node.js or other environments that do asynchronous or idempotent module loading with runtime dependency resolution. This called “module” compilation. Here, the
--moduleflag you pass totscmatters, and the only valid thing to do is side-by-side compilation, because loading a single file as a module is (generally) how the module loaders in node.js, etc work.In module compilation, you use the
exportkeyword on a top-level object (function, class, module, interface, or var) to control what’s available to code that refers to you usingimport. You should only ever have/// <reference>tags that point to.d.tsdeclaration files, because the module-based runtime loaders don’t have a notion of loading a naked JS file. You won’t compile with--out.You never want to mix and match these compilation modes, because it simply is not going to work. In fact, in 0.8.2.0,
tscwill simply issue an error if you try to do this.