Typescript for Node
How to get started on a Typescript CLI project using yarn for package management and nvm for managing node versions.
Set up the overall environment
nvm install lts/*
npm install -g strip-json-comments-cli
npm install -g yarnSet up the project directory. I use ~/src/<project>
mkdir <applicationname>
cd <applicationname>
node --version > .nvmrc
yarn init -yExample package.json for the typescript-nodejs-example application.
{
"name": "typescript-nodejs-example",
"version": "0.1.0",
"main": "index.js",
"author": "Mark C Allen <mark@markcallen.com>",
"license": "MIT"
}Add typescript
yarn add -D typescript @types/node tsx rimrafCreate a tsconfig.json
# create a tsconfig.json file
npx tsc --init --rootDir src --outDir dist \
--esModuleInterop --target esnext --module nodenext \
--verbatimModuleSyntax false --allowJs true --noImplicitAny true
# remove the comments and whitespace so that it's readable
cat tsconfig.json | strip-json-comments --no-whitespace | \
jq -r . > tsconfig.pretty.json && mv tsconfig.pretty.json tsconfig.json
# add in node as a type
npx json -I -f tsconfig.json -e 'this.compilerOptions.types=["node"]'The resulting tsconfig.json is like this:
{
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"module": "nodenext",
"target": "esnext",
"types": [
"node"
],
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"strict": true,
"jsx": "react-jsx",
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowJs": true,
"noImplicitAny": true
}
}Let's create a Hello World script and test
mkdir srcAdd the following to src/index.ts
console.log('hello world!!');
// Keep the process alive until Ctrl-C
process.stdin.resume();
// Optional: Handle graceful shutdown on Ctrl-C
process.on('SIGINT', () => {
console.log('\nGoodbye!');
process.exit();
});src/index.ts
Add a helper script, build.
npm pkg set "scripts.build"="rimraf ./dist && tsc"
yarn buildNow, let's add a start script
npm pkg set "scripts.start"="node dist/index.js"Running yarn start will return. Press ctrl-c to exit.
yarn run v1.22.22
$ node dist/index.js
hello world!!
^C
Goodbye!Adding Development
Since we don't want to compile this each time, let's add a dev script to use tsx to compile and run the script in one command.
npm pkg set "scripts.dev"="tsx src/index.js"Now, we can run and again press ctrl-c to exit.
yarn dev
yarn run v1.22.22
$ tsx src/index.js
hello world!!
^C
Goodbye!Setup Git
Let's add everything to git
git init
cat << EOF > .gitignore
.env
yarn-error.log
dist/
node_modules/
EOF
git add .
git commit -m "First checkin" -aWe now have a project set up for TypeScript to use Node.js.
I've shared this project on github as an example: https://github.com/markcallen/typescript-nodejs-example