Directory structure for TypeScript projects

codematix picture codematix · Mar 4, 2016 · Viewed 28.6k times · Source

What would be an idiomatic directory structure for a TypeScript project?

I would like the following features in such a structure:

  1. Separate directories for TypeScript source code and transpiled JavaScript
  2. Separate directories for project source code and test code
  3. Mechanism to resolve references across tests and source code.

Answer

Angad picture Angad · Mar 4, 2016

Separating generated JS from source TS

I would recommend generating a single-file output. Be it browser or for Node, its just a better idea. Bear in mind that most IDEs can hide .gitignored files, so an uncluttered file-pane shouldn't be a problem to attain, even if you let the .js files sit right next to their .ts files.

You can technically use --outDir to output the way you want by setting up your tsconfig.json appropriately.

Separating tests from source

This is fairly trivial! Just maintain a /tests. Imports work simply by directory traversal like so import {MyClass} from "../src/modules/my-class" (where the ../ is to get out of /tests).

Mechanism to resolve references

This is more challenging in the browser than on Node — the latter has requires working out of the box for TypeScript.

On the browser

Strongly recommend you go with something like webpack, but if you insist on living life on the dangerous side, here is a browser-friendly require that I use to rapidly iterate on TypeScript code without having a build process setup.

require() for the browser

  • Not for the weak hearted — this is tech debt you will accumulate

Since absolute paths are necessary for working web imports, here is how you can use my require() hack with TypeScript (typically for a fast debugging session that doesn't require rebuilding).

/entities/user.ts

import {Username} from "../entities/username";
import {Password} from "../entities/password";

export class User {
    username: Username;
    password: Password;
}

Where Username and Password are exported classes in /entities/username.ts and /entities/password.ts respectively.

While the ../entities/ might seem extraneous, notice that it is essential for the browser to have appropriate absolute paths to our Username and Password entities. :)