Including Local Files in Compiled TypeScript

When working with TypeScript I like to separate my code into files and folders for the sake of maintainability, cleanliness and organisation.

However as someone new to the language I had a bit of trouble getting those files working together and compiling as I expected. Some search results confused me with the use of the import keyword and it all seemed more complicated than such a simple task should be – they involved including other scripts to handle asynchronous loading and dependency handling, etcetera…

I’m talking about local files that you just want to be included in compilation – not external modules or something to be lazy loaded, so of course it should be very simple. Once I found out I thought I’d post it here as a nice, simple reference for anybody who may bump into the same problem.


If you want TypeScript use file foo.ts in another file called main.ts, just include a reference at the top of main.ts like this:

///<reference path="foo.ts"/>

Now foo.ts will be compiled to a separate foo.js file. TypeScript can now compile main.ts as though foo.ts was loaded beforehand, but you still need to load it yourself:

<script src="foo.js"></script>
<script src="main.js"></script>

I personally expected the referenced file to be compiled into main.js so I’d only need to use one script tag and, more importantly, so my HTML wouldn’t be dependent on the file structure I used behind the scenes.

To meet this expectation, explicitly specify main.js as the output file when compiling:

tsc [--watch] --out main.js main.ts

Author: Bilal Akil

Husband of Joy. Programming hobbyist and professional.

Leave a Reply

Your email address will not be published. Required fields are marked *