概要
なんか今更感ありますが、hubotです。
async/await使いたくなったとかいろいろあって、hubotをtypescriptでかけるようにしてみたいと思います。
あと、せっかくなのでeslintとprettierを導入して、ちゃんとしたコードがかけるようにします。
やったこと
1. yarn init
package.jsonを作ります
yarn init
2. yarn add typescript
typescriptをインストール
yarn add -D typescript
3. tsconfig.jsonを追加
srcにソースを配置します。
コンパイル結果はhubotの標準?だと思われるscriptsディレクトに出力します
{
"compilerOptions": {
"sourceMap": true,
"target": "es5",
"outDir": "./scripts",
"rootDir": "src"
}
}
4. package.json書き換え
package.jsonに以下を追加して、yarn buildでコンパイルできるようにします
"scripts": {
"build": "tsc"
}
5. eslintとprettierを設定(linterが不要なら不要です)
エディタを設定すれば、書きながらでも怪しいコードを指摘してくれるし、保存時にprettierが動くようにすれば、コードの品質を一定程度保ってくれてありがたいです。
インストール
yarn add -D @typescript-eslint/eslint-plugin \
@typescript-eslint/parser \
eslint \
eslint-config-prettier \
eslint-plugin-prettier \
prettier
.eslintrc.jsを作成
module.exports = {
extends: ["eslint:recommended", "plugin:prettier/recommended"],
plugins: ["@typescript-eslint", 'prettier'],
parser: "@typescript-eslint/parser",
parserOptions: {
sourceType: "module",
project: "./tsconfig.json",
},
env: {
browser: true,
node: true,
es6: true,
},
rules: {
"no-console": "warn",
"@typescript-eslint/adjacent-overload-signatures": "warn",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
}
}
.prettierrcを追加する
{
"singleQuote": true,
"semi": false
}
6. hubotを導入する
ここまでで、typescriptが使えるようになっているので、いつもの調子でhubotを導入します。
yoをglobalにインストール
npm i -g yo generator-hubot
hubotをインストールします。
package.jsonをoverriteするかきかれるのでnにしましょう
yo hubot
scriptsディレクトリはコンパイル結果を出力するので.gitignoreに登録しておきます。
+ scripts
bin/hubotを修正して、実行前にtypescriptをコンパイルするようにします。
# !/bin/sh
set -e
yarn
yarn build
export PATH="node_modules/.bin:node_modules/hubot/node_modules/.bin:$PATH"
exec node_modules/.bin/hubot --name "tsbot" "$@"
7. src/main.tsを追加
その前にhubotのtypesをインストールします
yarn add -D @types/hubot
src/main.tsを作成します。
これがメインのファイルになります。
import * as hubot from 'hubot'
module.exports = (robot: hubot.Robot<any>): void => {
robot.respond(/hello/i, (msg: hubot.Response<hubot.Robot<any>>) => {
msg.reply('world!')
})
}
8. 実行します
ここまでで、実行できます。
bin/hubot
tsbot> tsbot hello
tsbot> Shell: world!
tsbot>
あとは、すきな機能を実装するだけです。
async/awaitも使えて、型もつかえていいかんじです!