[Babel] babel-preset-jsdoc-to-assert で JSDoc から assertion を自動生成する

babel env option を利用して、開発時に jsdoc-to-assert させる。

[markdown]
> * [JSDocをランタイムassertに変換するBabelプラグインを書いた | Web Scratch](http://efcl.info/2016/03/25/jsdoc-to-assert/)
>
> ESLintで静的にJSDocのコメントをチェックできるvalid-jsdocとbabel-plugin-jsdoc-to-assertを合わせて使うようなイメージで書いています。

## インストール

preset をインストールする。

> * [azu/babel-preset-jsdoc-to-assert: Babel preset for jsdoc-to-assert.](https://github.com/azu/babel-preset-jsdoc-to-assert)

“`prettyprinted
% npm install –save-dev babel-preset-jsdoc-to-assert
“`

.babelrc に jsdoc-to-assert を設定する。

“`:.babelrc
{
“presets”: [
“es2015”
],
“env”: {
“development”: {
“presets”: [
“power-assert”,
“jsdoc-to-assert”
]
},
“production”: {
“plugins”: [
“babel-plugin-unassert”
]
}
}
}
“`

## 実行

[前回まで](https://www.d-wood.com/blog/2016/11/10_8533.html)は、assert を直接 lib ファイルに書いた状態だった。

> * [sandbox-es6/math.es6.js at 08f88ed3648332e8fe4e8aade25879b9692bd8bf · DriftwoodJP/sandbox-es6](https://github.com/DriftwoodJP/sandbox-es6/blob/08f88ed3648332e8fe4e8aade25879b9692bd8bf/src/lib/math.es6.js)

上述のサンプルコードであれば、下記3行が不要になる。

“`javascript
const assert = require(‘assert’);
assert(typeof x === ‘number’);
assert(typeof y === ‘number’);
“`

[DriftwoodJP/sandbox-es6](https://github.com/DriftwoodJP/sandbox-es6) であれば、`BABEL_ENV=development babelify ` のような形でオプションを渡せば、jsdoc-to-assert が有効となる。

以下が生成された。

“`javascript
if (!(typeof x === “number”)) {
console.assert(typeof x === “number”, ‘Expected type: @param {number} x\nActual value:’, x, ‘\nFailure assertion: typeof x === “number”‘);
}
if (!(typeof y === “number”)) {
console.assert(typeof y === “number”, ‘Expected type: @param {number} y\nActual value:’, y, ‘\nFailure assertion: typeof y === “number”‘);
}
“`

以下にまとめた。

> * [DriftwoodJP/sandbox-es6: sandbox es6(2015)](https://github.com/DriftwoodJP/sandbox-es6)

## 補遺

> * [jsdoc-to-assert を試す – アカベコマイリ](http://akabeko.me/blog/2016/08/jsdoc-to-assert/)
>
> JavaScript の型チェックといえば Flow や TypeScript だが、前者は型の定義ファイルが必要で、後者は言語自体を拡張しているため導入コストが少々、高い。
[/markdown]