Danh mụcThẻBài viết

admin

I'm a Full-stack developer

Thẻ

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
Create Project with Express + TypeScript + ESLint + Auto Reload
Ngày đăng: 12/06/2023

While building a server project written in JavaScript and using Node.js + Express is simple. But when your project is developed every day and need to increase the number of developers from other countries, Instead of using JavaScript we will use TypeScript to code and handle errors more efficiently and quickly.


In this article, I introduce to you how to initialize an Express + TypeScript project.


Create package.json
mkdir node-express-typescript
cd node-express-typescript
yarn init --yes


The default config will be created
{
    "name": "node-express-typescript",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "type": "module",
    "keywords": [],
    "author": "",
    "license": "ISC"
}


Create a server with Express
yarn add express dotenv


Create file ./node-express-typescript/src/index.js
const express = require('express');
const dotenv = require('dotenv');

const app = express();
const port = process.env.PORT;

app.use(express.json());
app.use(express.static('public'));
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  return console.log(`http://localhost:${port}`);
});


Set port in .env file
PORT=3000


To start the server, we run the command below
node src/index.js


Express server is already running, you can try using postman to check.


Setup TypeScript, Install dev dependencies
yarn add typescript @types/express @types/node --dev


In package.json will be like below
{
    "devDependencies": {
        "@types/express": "^4.17.14",
        "@types/node": "^18.11.11",
        "typescript": "^4.9.3"
    }
}


Create tsconfig.json
npx tsc --init


{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": "./",
    "rootDir": "./",
    "outDir": "./dist",
    "paths": {}
  },
  "include": ["./src"],
  "exclude": ["node_modules"]
}


Change the file ./node-express-typescript/src/index.js to ./node-express-typescript/src/index.ts
import express from 'express';

const app = express();
const port = 3000;
app.use(express.json());
app.use(express.static('public'));
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  return console.log(`http://localhost:${port}`);
});


Setup auto reload
yarn add nodemon ts-node --dev


Create nodemon.json
{
  "watch": ["src"],
  "ext": "ts",
  "exec": "ts-node ./src/index.ts"
}


Update script in package.json
{
    scripts": {
        "build": "npx tsc",
        "start": "node dist/index.js",
        "dev": "nodemon"
    }
}


Start server
yarn dev


Now that the server is working, you can change the content of the file index.ts res.send('Hello World!'); to res.send('Hello World Update!'); and then trigger postman again and see the change as shown below


Setup ESLint, Install dev dependencies
yarn add eslint eslint-config-prettier eslint-config-standard-with-typescript prettier @trivago/prettier-plugin-sort-imports @typescript-eslint/eslint-plugin --dev


npx eslint --init


Change the content of the file .eslintrc.json
{
  "env": {
    "node": true,
    "commonjs": true
  },
  "root": true,
    "extends": ["standard-with-typescript", "eslint:recommended", "plugin:prettier/recommended"],
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "parser": "@typescript-eslint/parser",
    "project": "./tsconfig.json"
  },
  "plugins": ["react"],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": "off"
  }
}


Create .prettierrc
{
  "semi": true,
  "tabWidth": 2,
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "all",
  "importOrder": [
    "<THIRD_PARTY_MODULES>",
  ],
  "importOrderSeparation": true, 
  "importOrderSortSpecifiers": true,
  "plugins": []
}


Update script in package.json
"scripts": {
    "build": "npx tsc",
    "start": "node dist/index.js",
    "dev": "nodemon",
    "lint": "eslint .",
    "lint:fix": "eslint --fix",
    "format": "prettier --write './**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc"
  },


Run format code
yarn format



Good luck with your installation!!!

Đề xuất

TypeScript Design Pattern - Abstract Factory
admin07/08/2023

TypeScript Design Pattern - Abstract Factory
The abstract factory pattern is one of five design patterns in the Creational Design Pattern group. The abstract factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.
ĐINH THÀNH CÔNG - Software Developer
admin12/01/2024

ĐINH THÀNH CÔNG - Software Developer
Cong Dinh - Software Developer - My personal website, where I write blogs on a variety of topics and where I have some experiments with new technologies.
How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
Mới nhất

Writing a Data Transformation Pipeline Using Go
admin20/03/2024

Writing a Data Transformation Pipeline Using Go
In this article, I will show how to implement data processing using the Go programing language with a simple tutorial.
Microservice in a Monorepo
admin22/06/2023

Microservice in a Monorepo
Microservice in a Monorepo
How to integrate ChatGPT-3.5 Turbo into Node.js
admin10/01/2024

How to integrate ChatGPT-3.5 Turbo into Node.js
Step-by-Step Guide to Incorporating ChatGPT-3.5 Turbo into Node.js for Basic ReactJS Applications
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Góp ý
Họ & Tên
Số điện thoại
Email
Nội dung
Tải ứng dụng
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About