Table of contents
Base setup
Before we start configuring and installing dependencies, let's first create a base project:
mkdir your-project && cd your-project
mkdir src
Setup node project:
npm init --yes
Create project source code:
touch src/main.ts src/calc.ts
src/calc.ts:
export const add = (x: number, y: number) => x + y;
src/main.ts:
import * as fs from 'fs';
import { add } from './calc';
console.log(add(2,2));
fs.writeFile('text.txt', 'Content.', (err) => {
if (err) throw err;
console.log('File created.');
});
Setup TypeScript
Install typescript dev dependencies:
npm install typescript @types/node --save-dev
Init typescript:
tsc --init
And configure tsconfig.json to look like this:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"allowJs": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Setup Nodemon
Install
npm install --save-dev ts-node nodemon
Create nodemon configuration file:
touch nodemon.json
nodemon.json:
{
"watch": ["src"],
"ext": ".ts,.js",
"ignore": [],
"exec": "ts-node ./src/main.ts"
}
Add a
...
"start:dev": "nodemon"
...
Now if you run
Before we wrap up, it would be great to add production scripts.
First install
npm install --save-dev rimraf
after, add this two scripts to package.json:
...
"build:prod": "rimraf ./dist && tsc",
"start:prod": "npm run build:prod && node dist/main.js"
...
Now run command