Saulo Vallory
Saulo Vallory

Reputation: 979

Typescript modules per folder

I have the following structure for my app

app/
 |-common/
 |-modules/
 | |-projects/
 | | |-models.ts
 | | |-controller.ts
 | | |-commands.ts
 | | '-module.ts
 | |-login/
 | '-dashboard/
 |-typings/
 '-app.ts

Files inside common/, login/ and dashboard/ were omited for brevity, but assume the folders contain files, there is no cross-reference between modules, but modules reference files inside common/ freely.

I'm trying to find a way to make typescript compile this project into this...

app/
 |-common.js
 |-modules/
 | |-projects.js
 | |-login.js
 | '-dashboard.js
 '-app.js

I'm using internal modules, so a file like models.ts looks like this:

/// <reference path='../../common/ModelCollection.ts' />

module Sparrow.Projects {
  'use strict';

  // . . .

  export class Company {
    id: number;
    name: string;

    get text() {
      return this.name;
    }
  }
}

I tried combining the typescript files on a per folder basis and then compiling using --outDir but managing the references has been harder than I initially thought. In fact, I couldn't get it to work.

Any suggestions?

Upvotes: 3

Views: 1539

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221192

You'll want to use separate compilation to do this.

Example:

common/utils.ts

function utilFn1() { ... }

common/fooManager.ts

/// <reference path="utils.ts" />  
class FooManager () { ... utilFn1(); ... }

modules/dashboard/panel.ts

/// <reference path="../../common.d.ts" />
var panel = new FooManager();

modules/dashboard/main.ts

/// <reference path="../../common.d.ts" />
/// <reference path="panel.ts" />
panel.load();

Then your compilation steps look like this:

tsc --out common.js --declaration common\utils.ts common\fooManager.ts
tsc --out modules\dashboard.js modules\dashboard\panel.ts modules\dashboard.main.ts

One other additional thing you can consider is having a common "references.ts" file per output that simply has reference tags pointing to all the files. For example, common/references.ts would reference utils.ts and fooManager.ts, and those files would in turn reference references.ts. This makes it clearer to understand which files are part of a logical group, and puts you in more explicit control of the ordering of the output. In that case, you would simply pass references.ts as the only input to tsc rather than passing all of the files individually. See also the "References" section of this blog post


A useful clarifying addendum from the asker that I think is worth adding:

I would like to stress that it's crucial to reference declaration files (.d.ts) instead of .ts files when referencing other modules. That and splitting the compilation so the declaration files can be automatically generated did the trick.

Upvotes: 2

Related Questions