カスタムルール作成
ESLintは便利だがJavaScriptのコーディングをしていると特定のテキストや関数の使用をルールで禁止にしたいことがある。
しかし、目視で確認するのは大変なのでVS CodeとESLintを使用したカスタムルールの作成方法を簡単に説明します。
サンプルでは「Hello」というテキストの代入とsayHello()という関数があった場合はVS Codeで自動検出して存在する場合は赤の下線でわかるようになります。(細かい説明は割愛)
カスタムルール作成の準備
まず、適当な空のディレクトリ名(sample)を作成してcdでsampleに移動後、以下のコマンドを実行する。
npm init -y && npm i -D eslint eslint-plugin-rulesdir && touch index.js && touch .eslintrc.js && mkdir rule
index.jsの中身は下記のようにする。
function sayHello() { console.log('Hello') } sayHello()
.eslintrc.js(不可視ファイル)の中身は下記のようにする。
const rulesDirPlugin = require('eslint-plugin-rulesdir') rulesDirPlugin.RULES_DIR = './rule' module.exports = { parserOptions: { ecmaVersion: 6 }, plugins: ['rulesdir'], rules: { 'rulesdir/no-hello': 'error', 'rulesdir/no-say-hello': 'error', } }
ruleというディレクトリが作成されているので中にno-hello.jsとno-say-hello.jsを作成して中身を下記のようにする。
// no-hello.js module.exports = { create: function(context) { return { Literal: function(node) { if (/Hello/.test(node.value)) { context.report({ node: node, message: 'Helloは使用禁止' }); } } }; } };
// no-say-hello.js module.exports = { create: function(context) { return { CallExpression: function(node) { if (node.callee.name === 'sayHello') { context.report({ node: node, message: 'sayHello()は使用禁止' }) } } } } }
以上の手順が完了したらでVS Codeを再起動してindex.jsのコードを見ると、該当箇所が赤の下線でわかるようになる。
赤の下線をマウスオーバーすると詳細が表示され、VS Code下部の「問題」にも一覧で表示される。
サンプルファイルも作成したのでうまくいかない場合はこちらをダウンロードしてnpm install後にどこが間違っているのか確認すると良いだろう。