Note: This post originally appeared at Codeburst
At Setfive Consulting we’ve become big fans of using TypeScript on the frontend and have recently begun adopting it for backend nodejs projects as well. We’ve picked up a couple of tips while setting up these projects that we’re excited to share here!
As you can see above you’ll want a tsconfig.json file to configure the behavior of the TypeScript compiler. tsconfig.json is a special JSON configuration file that automatically sets various flags for you when you run “tsc” with it present. You can see an exhaustive list of the available options at here. We’ve been using the following as a solid starting point:
From a build perspective this will configure a couple of things for you:
- The compiler will output into a “dist/” folder
- And it’ll compile all of your source files under the “src/” directory
ts-node and nodemon
ts-node is basically a wrapper around your nodejs installation that will allow you to run TypeScript files directly, without invoking the compiler. Their Readme highlights how it works:
So with ts-node you’ll be able to run something like “ts-node src/index.ts” to run your code.
nodemon is the second piece of the puzzle. It’s a node utility that will monitor your source files for changes and automatically restart a node process for your. Perfect for building express or any server apps! We’ve been using the following nodemon.json config file:
And then you’ll be able to just invoke “nodemon” from the root of your project.
Remember “@types/” packages
import * as _ from "lodash"; console.log(_.range(0, 10).join(","));
Will result in a TypeScript error:
src/index.ts(1,20): error TS7016: Could not find a declaration file for module ‘lodash’. ‘/home/ashish/Downloads/node_modules/lodash/lodash.js’ implicitly has an ‘any’ type.
Try `npm install @types/lodash` if it exists or add a new declaration (.d.ts) file containing `declare module ‘lodash’;`
npm install — save @types/lodash
And now the compiler will run without any errors.
Off to the races!
At this point you should have a solid foundation for a TypeScript powered nodejs project. You’ll be able to take advantage of TypeScript’s powerful type system, nodejs’ enormous library ecosystem, and enjoy a easy to use “save and reload” workflow. And as always, I’d love any feedback or other tips!
Thinking about adopting TypeScript at your organization? We’d love to chat.