카테고리 없음

mongoose를 이용한 MongoDB 연동 실습2 ES 모듈 적용

cheon seung hyeon 2023. 4. 15. 23:36

 

...
  }, 
  "type": "module"
}

리액트 프로젝트에서 자주 사용되는 ES 모듈 import와 export 문법은 Node.js에서 사용할 때는 package.json 파일 에 모듈러 타입을 설정하면 됩니다.

 

👉🏻 ESLint에서 import/export 구문을 사용해도 오류로 간주하지 않도록 sourceType 값을 “module”로 설정

...
     "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module"   
},

 

ES Module 형식으로 변경

export const write = ctx => {
  ...
};

export const list = ctx => {
   ...
};
export const read = ctx => {
   ...
};

export const remove = ctx => {
   ...
};

export const replace = ctx => {
   ...
};

export const update = ctx => {
   ...
};

index.js 파일도 변경

 

// src/api/posts/index.js

const Router = require('koa-router');
const postsCtrl = require('./posts.ctrl');

->

import Router from 'koa-router';
import * as postsCtrl from './posts.ctrl.js';

 src/api/posts/index.js

 

// src/api/index.js

const Router = require('koa-router')
const posts = require('./posts')

->

import Router from 'koa-router';
import posts from './posts/index.js';

 src/api/index.js

 

// src / index.js

require('dotenv').config();
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const mongoose = require('mongoose');

const api = require('./api');

->

import dotenv from "dotenv";

dotenv.config();

import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import mongoose from 'mongoose';

import api from './api/index.js';

 src/index.js