ES2015(ES6) でスクリプトを書ける Hubot 環境を作る

Hubotのスクリプトを書くとき、今更coffeeは辛いのでES2015(ES6)で運用できる環境を作りたくなりました。

STEP1: Hubotのスケルトンを作成する

まず、Hubotのスケルトンを作成します。公式ドキュメント がよいです。

本当は対話的に各項目を埋めていくんだけど、オプションで指定するとコマンド一発でいけます。サイコーですね。

npm install -g yo generator-hubot
mkdir aokibot && cd aokibot && \
  yo hubot \
    --owner="Yoshiki Aoki <yoshiki_aoki@example.com>" \
    --name="aokibot" \
    --description="Excellent working bot" \
    --adapter=slack

試しに実行するにはbin/hubotで起動します。

STEP2: ES2015の環境を整える

babelを使ってES2015で書いたコードをES5に変換します。 変換に必要なモジュールをnpmでインストール。それと、ES2015のソース用ディレクトリとビルド後のディレクトリを作成しておきます。

npm i --save-dev babel babel-cli babel-preset-es2015
mkdir src builds

STEP3: サンプルスクリプトを書いてみる

src/example.jsにES2015の文法を使って書いたサンプルスクリプトを追加します。

// Description:
//  Example scripts for you to examine and try out.
//
// Notes:
//  They are commented out by default, because most of them are pretty silly and
//  wouldn't be useful and amusing enough for day to day huboting.
//  Uncomment the ones you want to try and experiment with.
//
//  These are from the scripting documentation: https://github.com/github/hubot/blob/master/docs/scripting.md

module.exports = (robot => {
  robot.hear(/hello/i, res => {
    res.send("World!!");
  });
});

Hello World!!

STEP4: 起動設定をする

ビルドして起動してってあんまりゴチャゴチャさせたくないですよね。なので、トランスパイル、起動はnpm経由でやるのがスマートです。

package.jsonにビルドや起動の設定を追加します。

まず、run-scriptbuildを追加してトランスパイルを行います。

"build": "babel src --presets es2015 --out-dir ./builds"

そして、起動スクリプトにbin/hubotを指定します。この時、-rオプションでbuildsディレクトリを指定してやることによって、素の(?)スクリプトはscripts、ES2015からトランスパイルされたスクリプトはbuildsと住み分けることができます。

"start": "bin/hubot -r builds"

最後に起動するときはnpm run build && npm startとすれば起動します。 が、そんなダサい方法は使いたくありません。 npm startだけで終わらせたいので、prestartnpm run buildを指定してあげます。

"prestart": "npm run build"

トランスパイルしてから起動するコマンドはnpm startだけでよくなりました。スマートなのはいいですね。

最後に差分貼っておきます。

diff --git a/package.json b/package.json
index 71768eb..879620b 100644
--- a/package.json
+++ b/package.json
@@ -4,6 +4,11 @@
   "private": true,
   "author": "Yoshiki Aoki <yoshiki_aoki@example.com>",
   "description": "Excellent working bot",
+  "scripts": {
+    "build": "babel src --presets es2015 --out-dir ./builds",
+    "prestart": "npm run build",
+    "start": "bin/hubot -r builds"
+  },
   "dependencies": {
     "hubot": "2.18.0",
     "hubot-help": "0.1.3",

Problems

deprecated documentation syntax というINFOメッセージが出る

トランスパイル後のファイルには先頭に"use strict"がついている。 これが、原因で builds/example.js is using deprecated documentation syntax というメッセージが出てしまう。悪影響は全くないけども、解決する方法があるのであれば解決したいですね。

References