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>
cd <applicationname>
node --version > .nvmrc
yarn init -y
Example package.json for the typescript-commonjs-example
application.
{
"name": "typescript-commonjs-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 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
Add 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 build
Now 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" -a
Now we have a project set up for typescript.
I've shared this project on github as an example: https://github.com/markcallen/typescript-commonjs-example
Next steps are to add a Dockerfile for Typescript