Madogiwa Blog

主に技術系の学習メモに使っていきます。

ESLintの`no-restricted-syntax`を使ってASTを元に任意の変数名への任意のメソッド呼び出しを禁止したりするメモ📝

ESLintのno-restricted-syntaxが便利だったので使い方をメモ📝

eslint.org

例えばVue3へのアップデート時に以下のようなVue Test Utilsの変更がありアップデートするまでwrapper.destroyを禁止したいとします。

Wrapper API (mount)
destroy: renamed to unmount to match Vue 3 lifecycle hook name.
Migrating from Vue Test Utils v1 | Vue Test Utils

こういう場合、カスタムルールを書かなくても以下のような感じでno-restricted-syntaxを使って簡単に禁止にできます。

module.exports = {
  rules: {
    "no-restricted-syntax": [
      "error",
      {
        selector: "CallExpression[callee.property.name='destroy'][callee.object.name='wrapper']",
        message: "Calling wrapper.destroy() is not allowed",
      },
    ],
  },
};

CallExpression[callee.property.name='destroy'][callee.object.name='wrapper']でASTを元にwrapper.destoryに合致したらエラーにできるというわけですね。

カスタムルールを作らずにこういうのができるな便利ですね! かつGitHub Copilot Chat等で生成してもらいやすいのも非常に便利でした🤖✨