Initialize npm project by running the following command:
npm init -y
Install Express
npm install express
Install Typescript
npm install --save-dev typescript
Setup tsconfig.json file
npx tsc --init
Set the config file to looks similar to the following:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "./dist"
}
}
target
- Leave the default option es2016.
module
- Leave the default option commonjs.
skipLibCheck
- Setting this to true can help time.
outDir
sets where the compiled file will be generated.
Setup eslint
npx eslint --init
Install type support for express
npm i -D typescript @types/express
Build and run
npm run Build
npm start
Setup docker
Create a new Dockerfile
and add the content from below.
FROM node:18-alpine AS build-env
WORKDIR /app
# copy source files
COPY ./src/ ./src/
# copy required config files
COPY tsconfig.json package.json package-lock.json ./
# update npm to latest version
RUN npm install -g [email protected]
# install dependencies and build
RUN npm ci
RUN npm run build
# this step will create the actual docker image used for deployment
FROM gcr.io/distroless/nodejs18-debian11
COPY --from=build-env /app /app
WORKDIR /app
CMD ["dist/index.js"]
To create the image run
docker build -t example-api .
To run the image run
docker run --rm -p 8080:8080 -t example-api
We will use ava
as the unit test runner. To start run the command:
npm init ava
Setup config inside package.json
"ava": {
"nodeArguments": [
"--loader=ts-node/esm"
],
"typescript": {
"compile": "tsc",
"rewritePaths": {
"src/": "dist/"
}
}
}
Add coverage support
npm install --save-dev c8
Update test (in package.json) script to use coverage
{
"test": "c8 ava"
}