Typescript for CommonJS

How to get started with a typescript 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 yarn

Set up the project directory. I use ~/src/<project>

mkdir <applicationname>
node --version > .nvmrc
yarn init -y

Example package.json for the tool1 application.

{
  "name": "tools1",
  "version": "0.1.0",
  "main": "index.js",
  "author": "Mark C Allen <mark@markcallen.com>",
  "license": "MIT"
}

Add typescript

yarn add -D typescript @types/node ts-node nodemon rimraf

Create a tsconfig.json for a common module

npx tsc --init --rootDir src --outDir dist \
--esModuleInterop --resolveJsonModule --lib es6 \
--module commonjs --allowJs true --noImplicitAny true
cat tsconfig.json | strip-json-comments --no-whitespace | jq -r . > tsconfig.pretty.json && mv tsconfig.pretty.json tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "lib": [
      "es6"
    ],
    "module": "commonjs",
    "rootDir": "src",
    "resolveJsonModule": true,
    "allowJs": true,
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true
  }
}

Let's create a hello world script and test

mkdir src
echo 'console.log('\''Hello world!'\'');' > src/index.ts
npm pkg set "scripts.build"="rimraf ./dist && tsc"
yarn build
node dist/index.js

Setup Git

git init

cat << EOF > .gitignore
.env
yarn-error.log
dist/
node_modules/
EOF

git add .
git commit -m "First checkin" -a

Now we have a project setup for typescript.