Node JS
  • SetUp Node&NVM
  • Folder Structure
  • Setup NodeJS Project
  • Library
    • Awilix
    • Swagger
    • Express
    • Jest
      • Supertest
    • Prettier
    • Eslint & Tslint
      • Tslint & Prettier
      • Tslint Plugin Prettier
      • Config With Airbnb
    • Husky And Friends
    • Sentry
  • INFRASTRUCTURE
    • Docker
      • Docker image
      • Docker container
      • Docker Volume
      • Docker command
      • Docker Compose
      • Problem & Solution
    • SonarQube
      • How to use in Nodejs
    • NGinX
    • ดูเพิ่มเติม
  • Note
    • .env declare type
    • Learn Link
Powered by GitBook
On this page

Setup NodeJS Project

ติดตั้ง module พื้นฐานเพื่อให้ nodejs รัน typescript ได้

#Npm
npm init
npm install typescript --save-dev
npm install @types/node --save-dev 

#Yarn
yarn init
touch yarn.lock
touch .yarnrc.yml
กรณีต้องการ Node Resolution Strategy เป็น pnp
###.yarnrc.yml##
    enableGlobalCache: true
    nodeLinker: pnp
    yarnPath: ".yarn/releases/yarn-berry.cjs"
yarn add typescript @types/node -D
yarn dlx @yarnpkg/sdks vscode
##Reload Windows##
    Command + Shift + P ==> Reload Window

สร้างตัว tsconfig.json

#Npm
npx tsc --init --rootDir src --outDir build \ --esModuleInterop --resolveJsonModule --lib es7 \ --module commonjs --allowJs true --noImplicitAny true
#Yarn
yarn run tsc --init --rootDir src --outDir build \ --esModuleInterop --resolveJsonModule --lib es7 \ --module commonjs --allowJs true --noImplicitAny true

สร้างไฟล์ src/index.ts

mkdir src 
touch src/index.ts 

ติดตั้ง ts-node ,ts-node-dev

ts-node-dev เป็นโปรแกรมที่คอย update update โปรแกรมหรือ auto restart nodejs ของเราทันทีเมื่อเราทําการ กด save

#Npm
npm install --save-dev ts-node ts-node-dev
#Yarn
yarn add ts-node ts-node-dev -D
touch nodemon.json

ติดตั้ง rimraf

rimraf เป็น module สำหรับใช้ลบไฟล์ ที่ทำงานเหมือนกันการรันคำสั่ง rm-rf

#Npm
npm install --save-dev rimraf
#Yarn
yarn add rimraf -D

ติดตั้ง dotenv

dotenv เป็นไฟล์ที่ใช้เก็บค่าพารามิเตอร์ต่างๆที่ต้องการนำมาใช้กับ application

**ไฟล์นี้จะไม่ upload ขั้น git

npm install dotenv
touch .env

แก้ไขไฟล์

#nodemon.json
{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node ./src/index.ts"
}
#package.json
#Npm
"scripts": {
    "start": "run build && node build/index.js",
    "dev": " ts-node-dev --respawn --transpile-only ./src/index.ts",
    "build": "rimraf ./build && tsc"
    }
#Yarn
"scripts": {
     "start": "run build && node build/index.js",
    "dev": " ts-node-dev --respawn --transpile-only ./src/index.ts",
    "build": "rimraf ./build && tsc"
    }

คำสั่ง --save-dev

package.json จะแยกเป็น 2 ส่วนคือส่วนที่เป็น

devDependencies และ dependencies

การใช้ --save-dev จะเป็นการบันทึกว่า module ที่ install จะใช้ใน devDependencies

PreviousFolder StructureNextAwilix

Last updated 2 years ago