Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory structure for TypeScript projects

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.
like image 846
codematix Avatar asked Mar 04 '16 18:03

codematix


People also ask

Where are types stored in TypeScript project?

Like any other class, function or object, you can explicitly export and import types from . ts files. Maybe these are TS files that contain nothing but types. These can be kept in the root folder or locally in the specific directory.

What is the name of the file that manages TypeScript projects?

json / -p , existing TypeScript project properties will not be respected - all settings should be managed using your tsconfig file.


1 Answers

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. :)

like image 124
Angad Avatar answered Sep 23 '22 14:09

Angad