728x90
"2023 - 개정판 | 리액트를 다루는 기술 - 김민준 저자(글)"의 "22장 mongoose를 이용한 MongoDB 연동 실습"을 실습하는 과정에서 주의해야 하는 점을 정리했습니다.
Node.js에서 import/export 문법을 사용하기 위해서 ESM 모듈을 사용합니다. 현재 Node v20을 사용하는데 책에 있는 소스를 그대로 사용하면 실행시 오류가 발생하여 수정할 부분을 정리 했습니다.
1. package.json 수정
- ESM 문법은 Node.js v12부터 지원하고 있습니다. 책에서는 main.js에서 주요 구현을 만들어서 index.js에서 불러오게끔 했는데, 그럴필요 없이 index.js에서 구현하고 package.json 파일에 "type": "module" 을 추가 해 주면 됩니다.
- scripts에서 "-r esm" 부분을 삭제합니다.
// 이전소스
"scripts": {
"start": "node -r esm src",
"start:dev": "nodemon --watch src/ -r esm src/index.js"
},
// 변경소스
"scripts": {
"start": "node src",
"start:dev": "nodemon --watch src/ src/index.js"
},
- 최종소스 (package.json)
{
"name": "blog-backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"dotenv": "^16.3.1",
"eslint-config-prettier": "^9.1.0",
"esm": "^3.2.25",
"koa": "^2.14.2",
"koa-bodyparser": "^4.4.1",
"koa-router": "^12.0.1",
"mongoose": "^8.0.3"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.16.0",
"@typescript-eslint/parser": "^6.16.0",
"eslint": "^8.56.0",
"nodemon": "^3.0.2"
},
"scripts": {
"start": "node src",
"start:dev": "nodemon --watch src/ src/index.js"
},
"type": "module"
}
2. Node v14 부터는 ESM을 적용할 때 파일 확장자 까지 써주야 합니다.
import posts from './posts/index.js';
3. src/index.js 파일에서 .. dotenv 적용하는 부분 수정
// 기존소스
require('dotenv').config();
// 변경소스
import dotenv from 'dotenv';
dotenv.config();
728x90
'Node.js' 카테고리의 다른 글
Node.js 엑셀파일처리(xlsx) (0) | 2022.12.27 |
---|---|
Node.js 메일링 서비스(Nodemailer) (0) | 2022.12.26 |
Node.js MySQL 모듈 사용(mysql) - CRUD 샘플 코드 (0) | 2022.12.25 |
Node.js MySQL 모듈 사용(mysql) (0) | 2022.12.25 |
Node.js 첨부파일 업로드(multer) (0) | 2022.12.20 |