본문 바로가기

Studying Programming/Node.js

Node.js - Express

Node.js

node.js와 npm : 🔗Node.js 설명

Express 프레임워크

epxress 5.0.0 버전을 설치

npm install express@5.0.0

node.js가 CommonJS방식이 아닌 ESModule 사용으로 코드 변환.

4주차 내용에 더 있음 esmodule

[JS/Module] CommonJS와 ES Modules는 무엇일까?

// const express = require('express')  // -> CommonJS
import express from 'express'          // -> ES Module

const app = express()
const port = 3000

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

이때 기본적으로 .js파일은 CommonJS로 해석되기 때문에 package.js 파일에 type을 module로 지정해주어야 한다.

{
  "name": "node.js_study",
  "type": "module",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^5.0.0"
  }
}

ESmodule로 실행하게 되면 import 해야하는데 이때 .js를 항상 붙여 줘야 한다.

(자세한 차이점 👇)

node.js가 CommonJS방식이 아닌 ESModule 사용으로 코드 변환.

.vscode 에 settings.json 파일을 만들어 아래 코드를 입력

{
  "javascript.preferences.importModuleSpecifierEnding": "js"
}

vscode 설정 방법

Visual Studio Code 설정 방법 (Visual Studio Code: Settings) 정리

위 작성한 index.js 파일을 실행하기 ⬇️

node src/index.js

nodemon 모듈 사용하기

nodemon란?

• nodemon은 Node.js 애플리케이션의 변경 사항을 자동으로 감지하고 서버를 재시작해 주는 도구

• 코드 변경 후 매번 수동으로 서버를 껐다 켜야 하는 번거로움을 덜어줌

npm install --save-dev nodemon

nodemon은 배포시 사용하지 않는 모듈이기 때문에--save-dev 옵션으로 설치한다.

  • 이 옵션을 통해 package.json 파일의 devDependencies 섹션에 기록
  • 개발 중에만 필요하고, 배포 시에는 제외되는 패키지들을 설치할 때 사용

nodemon 설치후 파일 실행⬇️

npx nodemon src/index.js

package.js 에서 스크립트 설정후 사용할 수 있다.

'Studying Programming > Node.js' 카테고리의 다른 글

Node.js - EC6, 프로젝트 구조  (0) 2025.03.19
Node.js  (0) 2025.03.07