• node.js v12 이후부터는 ES Module이 지원
  • ES Module에서 import/export 문법을 사용 가능
  • node --version으로 버전 확인 (현재 버전은 v12.15.0)
  • package.json에 아래와 같이 추가하면 ES Module을 바로 사용
(...)
  "scripts": {
    "start": "node src esm src",
    "start:dev": "nodemon --watch src/ -r esm src/index.js"
  },
  "type": "module"
$ yarn add esm
exports.write = ctx => {
  const { title, body } = ctx.request.body;
  postId += 1;
  const post = { id: postId, title, body };
  posts.push(post);
  ctx.body = post;
}; 
  • export에 에러가 발생할텐데 .eslintrc.json에 아래와 같이 "sourceType": "module"을 추가
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  • 모든 .js의 파일에서 reuiqreimport/export로 변경
import Router from 'koa-router';
import posts from './posts';

const api = new Router();

api.use('/posts', posts.routes());

export default api;

+ Recent posts