necojackarc’s blog

A software engineer's blog who works for a web service company

Make Hubot Scripts Easily with Babel ES201x

The original post was published on Mar. 12, 2017, by me in Japanese.

Using Babel, you can easily make Hubot Scripts with ES201x.

TL;DR

  1. Configure your Hubot following necojackarc/hubot-babel-es201x
  2. Code your Hubot Scripts in src/bot directory with Babel ES201x

Prologue

I happened to need to make a bot for ChatOps, when I encountered Hubot written in CoffeeScirpt, which was left behind the times……

……

…………

It surprised me a bit that Hubot had never been committed for about 10 months.

I googled it*1 but couldn’t find good alternatives. So, I tried persuading myself that this frequency of update showed stability, Hubot already went through many troubles, and decided to adopt Hubot.

However, I no longer want to write CoffeeScript, so I’ve decided to write Hubot Scripts in ES201x with Babel.

How easy it is

It’s really easy because it requires only Babel. Plus, configuration of Babel is very simple.

How it works

Hubot loads .coffee and .js in src/scripts and scripts automatically.

The format of those files is expected as below:

module.exports = (robot) ->
  # your code here

In other words, these are Hubot Scripts.

Taking it into account, I added the following directories this time:

Directory Description
dist For files transpiled
src/bot For Hubot Scripts written in ES201x
src/lib For files written in ES201x*2

Simple explanation of the flow is below:

  1. Make scripts with ES201x in src
  2. Transpile files in src into dist
  3. Get a file in scripts to load transpiled Hubot scripts in dist/bot

Configuration

Generate Hubot following Getting Started With Hubot.

Introduce Babel and required preset and polyfill:

$ npm install -D babel-cli babel-polyfill babel-preset-env

Write Babel configuration in .babelrc:

{
  "only": [
    "src"
  ],
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Add build command to package.json:

{
  "scripts": {
    "build": "babel src -d dist"
  }
}

Put a script in scripts, which loads Hubot Scripts transpiled into dist:

'use strict';

const fs = require('fs');
const path = require('path');

const ROOT = "./dist/bot";

const stripExtension = path => path.split('.').slice(0, -1).join('.');

module.exports = (robot) => {
  fs.readdirSync(ROOT).forEach((dir) => {
    require(path.join('..', ROOT, dir)).default(robot);
  });
};

Make necessary directories finally.

$ mkdir -p src/bot src/lib

Write a sample to check Configuration

As a test, put the following Hubot Script in src/bot/konosuba.js and work it:

export default function(robot) {
  robot.hear(/アクア/, (res) => {
    res.reply('駄女神');
  });
}

Then, boot Hubot by bin/hubot:

hubot-babel-es201x> アクア様
hubot-babel-es201x> Shell: 駄女神

It works!

*1:12+ Frameworks to Build ChatOps Bots

*2:Prepared for JavaScripts files except for Hubot Scripts