I'm trying to work out the best way to split my application into a few CommonJS modules that can be consumed by other applications.
I have 5 TS classes, and I'd like to bundle them as a single CommonJS module. I then intend to publish this module to a private NPM repo, so it can be consumed by other applications. Ideally I'd like to package the relevant *.d.ts definition files with it.
What's the best way to do this? I'm using external TS modules, but these produce a separate CommonJS module per TS class.
As far as i know typescript doesn't support combining external modules yet. From their wiki on codeplex:
However, you can do a trick by using internal modules in typescript, since the tsc compiler has the ability to compile them into a single file, and then you can just add one more file with a
module.exports
directive for the whole namespace to make it a CommonJS module.Here is a step by step example. Let's say you have the following internal modules split into three files:
Validation.ts:
ZipCodeValidator.ts
LettersOnlyValidator.ts
If you compile these with with the --out parameter in the
tsc compiler
you can combine them into a single file. However, that doesn't make them a CommonJS module. To export them you use a trick to add one more ts file called ValidationExport.ts containing the export directive for the namespace:And then you can run the tsc command to compile everything to a single file called "validationmodule.js":
The output is a CommonJS module you can use in Node.js:
Having a separate CommonJS module per file is completely appropriate. All the
require
calls in TypeScript will translate to CommonJSrequire
calls in JavaScript, and the.d.ts
files will be picked up in the process. (If you're doing something silly likerequire
ing classes outside your source directory... stop.)You would only need to consider a packaging step if you intended to use this NPM package in other applications, in which case look into Browserify