ES6로 개발하기

개요

commonjs 문법 보다는 es6 문법을 사용하는게 더 편하고 추후 React SSR 연동할때도 꼭 필요한 작업이기에 어떻게 ES6문법으로 개발할 수 있는지 알아보자.
여러 블로그에서는 babel-node, @babel/register로 구현하는 방법이 소개되었지만, 필자는 webpack으로 하는 방법으로 구현해 보았습니다.

시작하기 전 챙겨야 하는 것

babel 관련된 library와 webpack이 프로젝트에 설치 되어 있어야 합니다.

webpack-node-externals

번들링 하지 말아야할 외부 모듈들을 정의 합니다.
backend 앱을 번들링 할때는 node_modules 안에 있는 library들은 번들링 하지 말아야 하기 때문입니다.

#webpack
npm install --save-dev webpack webpack-cli webpack-node-externals

#babel
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader

webpack.server.js

여기서 중요한건 target과 loader, externals 이다.

const path = require('path')
const nodeExternals = require('webpack-node-externals')

module.exports = {
  entry: './src/server.js',
  target: 'node', // built-in 모듈 제외 (fs, path, etc )
  output: {
    filename: 'server.js',
    path: path.resolve(__dirname, './dist'),
  },
  mode: 'development',
  optimization: {
    splitChunks: {
      chunks: 'all',
      name: false,
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/env', '@babel/preset-react'],
            plugins: ['@babel/plugin-proposal-class-properties'],
          },
        },
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.js'],
  },

  externals: [nodeExternals()], // ignore all modules in node_modules folder
}

server.js

import http from 'http'
import express from 'express'
import path from 'path'
import fs from 'fs'
const app = express()

const index = fs
  .readFileSync(path.resolve(__dirname, './index.html'))
  .toString()

app.use('/', express.static(path.resolve(__dirname, '../dist')))
app.get('*', (req, res) => {
  res.send(index)
})

const server = new http.Server(app)
server.listen(3000, (err) => {
  if (err) {
    return console.error(err)
  }
})

실행

webpack --config webpack.config.js && webpack --config webpack.server.js && node dist/server.js

마무리

이로써, es6문법을 서버쪽에서도 사용 가능하게 되었다.

react 문법과 맞추었으니 개발 속도가 더 빠를거 같다.

하지만, 로컬환경일 때는 코드 수정 후 자동으로 서버에 적용되어 브라우저에서 최신상태로 변경되어야 하는데 이부분을 챙겨야 겠다.

다음 글로 어떻게 할 수 있는지 알아보자