[javascript] Riot.js를 이용한 채팅 애플리케이션 개발

이번 블로그 글에서는 Riot.js를 이용하여 간단한 채팅 애플리케이션을 개발하는 방법에 대해 알아보겠습니다. Riot.js는 경량화된 UI 라이브러리로서 Vue.js나 React.js와 비슷한 구조를 가지고 있으며, 작은 규모의 프로젝트나 프로토타이핑에 적합한 프레임워크입니다.

준비물

이번 예제를 따라하려면 다음과 같은 도구와 라이브러리가 필요합니다.

프로젝트 생성

먼저 프로젝트 폴더를 생성한 후, 해당 폴더로 이동하여 다음 명령어를 실행해 Riot.js 프로젝트를 생성합니다.

$ npm init
$ npm install riot

Riot 컴포넌트 생성

Riot.js에서는 컴포넌트를 사용하여 UI를 구성합니다. 채팅 애플리케이션에서는 메시지를 보여주는 컴포넌트와 새로운 메시지를 입력하는 컴포넌트를 생성해보겠습니다.

먼저 chat-display.riot 파일을 생성하고 다음과 같이 컴포넌트를 정의합니다.

<chat-display>
  <ul>
    <li each={ message in messages }>{ message }</li>
  </ul>
</chat-display>

다음으로, chat-input.riot 파일을 생성하고 다음과 같이 컴포넌트를 정의합니다.

<chat-input>
  <form onsubmit={ sendMessage }>
    <input type="text" ref="messageInput" placeholder="메시지를 입력하세요">
    <button type="submit">전송</button>
  </form>

  <script>
    sendMessage(e) {
      e.preventDefault();
      const input = this.refs.messageInput;
      const { value } = input;

      if (value) {
        this.trigger('message', value);
        input.value = '';
      }
    }
  </script>
</chat-input>

애플리케이션 개발

이제 모든 컴포넌트를 불러와서 애플리케이션을 개발해보겠습니다.

먼저 app.js 파일을 생성한 후 다음과 같이 애플리케이션 코드를 작성합니다.

import riot from 'riot';
import './chat-display.riot';
import './chat-input.riot';

riot.mixin('message', {
  init() {
    this.on('message', message => {
      this.trigger('newMessage', message);
    });
  }
});

riot.mount('chat-display');
riot.mount('chat-input');

위 코드에서는 Riot.js의 riot.mixin을 사용하여 message라는 mixin을 정의하고, message mixin에서는 message 이벤트를 받아서 newMessage 이벤트를 발생시킵니다.

그리고 app.js에서는 chat-displaychat-input을 마운트하여 해당 컴포넌트를 실행시킵니다.

빌드 및 실행

이제 모든 준비가 끝났습니다. Webpack을 사용하여 프로젝트를 빌드하고 실행해보겠습니다.

먼저 webpack.config.js 파일을 생성한 후 다음과 같이 설정합니다.

module.exports = {
  entry: './app.js',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist'
  },
  module: {
    rules: [
      {
        test: /\.riot$/,
        exclude: /node_modules/,
        use: 'riot-tag-loader'
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.riot']
  }
};

위 설정에서는 Riot.js 파일을 .riot 확장자로 인식하도록 설정하고, Babel을 사용하여 ES6 문법을 변환합니다.

이제 다음 명령어를 실행하여 프로젝트를 빌드합니다.

$ npm install webpack webpack-cli webpack-dev-server babel-loader riot-tag-loader
$ npm install @babel/core @babel/preset-env babel-loader --save-dev
$ npm run build

빌드가 성공하면 dist 폴더에 bundle.js 파일이 생성됩니다. 이제 웹 서버를 실행하여 애플리케이션을 실행해보세요.

$ npm install webpack-dev-server --save-dev
$ npm run start

브라우저에서 http://localhost:8080 주소로 접속하면 채팅 애플리케이션을 확인할 수 있습니다.

마무리

이번에는 Riot.js를 이용하여 채팅 애플리케이션을 개발하는 방법을 알아보았습니다. Riot.js는 간결한 구조와 쉬운 문법으로 개발을 할 수 있으며, 작은 규모의 프로젝트나 프로토타이핑에 적합한 선택입니다.

더 자세한 내용은 Riot.js 공식 사이트를 참고해보세요.