First, let’s take a look at the project structure (which is also available at this Github repo):
|_ index.ts (or whatever name you want for your main file)
|_ dist (to be gitignored)
Now, let’s take a look at the
package.json file (please note that the command arguments should explain themselves, but if there’s anything unclear to you, please feel free to ask up in the comment section):
"dev": "ts-node --project src/tsconfig.json src/index.ts",
"start": "node dist/index.js",
"build": "tsc -p src/tsconfig.json",
"test": "TS_NODE_PROJECT=src/tsconfig.json mocha -r ts-node/register test/*.spec.ts",
"pretest": "npm run build",
"postinstall": "npm run build"
And then, the
"target": "ES5", // obviously, use whatever value you need
"lib": ["ES2015"], // obviously, use whatever value(s) you need
If I want to go even more minimal, I could ditch
ts-node and run
tsc every time I need to run or test my build. But so far I’m happy with running and testing my
.ts files directly.
I could use
ts-node-dev to take care of auto-reloading, but it’s beyond the scope of this post.
I could organize my test files in a totally different way (i.e. mix
*.spec.ts with the
.ts files under
src themselves) – then I’ll just need to edit the target pattern of my
mocha command). For this example, I’m happy to have my test files under their own directory.
PS: I could argue that I won’t even need
@types/mocha. For this example, my text editor (Atom) wanted it, so I pleased it, but your mileage might vary.
PPS: you may also ask why those things are in my
dependencies (and not
devDependencies), which is a valid question. For me, if I want to run tests and compile on the (production/build) server, I’ll list them as my main dependencies.
EDITS (Jan 20th, 2019):
npm run buildcommand used to be
tsc --build ...but the
--buildflag has now been dropped as it’s not really needed. Specifying a project file (
tsconfig.json) is much clearer. Please feel free to consult the tsc compiler references if you’re still curious about stuff.
tsconfig.jsonfile used to not include
rootDir. It does now, for even more clarity.
npm testcommand used to not include the
TS_NODE_PROJECT=src/tsconfig.jsonpart. It is now, because
ts-node/registeractually needs that to know which lib the tsconfig project file tells it to expect (kudos to this SO answer).
- pro-tip: did you know running
tsc --initwill create a default
tsconfig.jsonfile with verbose options (but mostly commented out for a bare minimal start) so you can tinker with? Do give it a try, you’ll love it.