javascriptnode.jstypescripttsc

Compiling multiple Typescript files


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:

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 ?


Solution

  • Your server.ts dependencies need to be modules that export their surface area with top-level export directives, and server.ts should load them using import directives. 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 .js file 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 --module flag you pass to tsc matters, 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 export keyword on a top-level object (function, class, module, interface, or var) to control what's available to code that refers to you using import. You should only ever have /// <reference> tags that point to .d.ts declaration 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, tsc will simply issue an error if you try to do this.