Madogiwa Blog

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

Vue 3.x系で削除された`Vue.extend`の使用をESLintで検知する方法MEMO📝

Vue 3.x系ではVue.extendが削除されています。

Vue.extend Removed Global API Application Instance | Vue 3 Migration Guide

そのためOptions APIでTypeScriptを利用したComponentではdefineComponentを使う等の変更が必要になります。

-- import Vue from 'vue'
-- export default Vue.extend({ /** ... **/ })
++ import { defineComponent } from 'vue'
++ export default defineComponent({ /** ... **/ })

このような変更に関してはeslint-plugin-vueで一部の破壊的変更が検知できますが、 v9.9.9においてVue.extendに関しては検知できなさそうだったのでカスタムルールで検知出来るようにしたのでやり方とかをメモ📝

eslint.vuejs.org

Vue.extendの使用をESLintで検知する

以下のESLintのカスタムルールをカスタムルール用のディレクトリに配置してあげれば検知できました!

'use strict'

module.exports = {
  meta: {
    type: 'problem',
    docs: {
      description: 'disallow using deprecated `Vue.extend` (in Vue.js 3.0.0+)',
      categories: ['vue3-essential'],
      url: 'https://eslint.vuejs.org/rules/no-deprecated-vue-extend.html'
    },
    fixable: null,
    schema: [],
    messages: {
      noDeprecatedVueExtend: '`Vue.extend` are deprecated.'
    }
  },
  /** @param {RuleContext} context */
  create(context) {
    return {
      /** @param {CallExpression} node */
      CallExpression(node) {
        if (
          node.callee.type === 'MemberExpression' &&
          node.callee.object.type === 'Identifier' &&
          node.callee.property.type === 'Identifier' &&
          node.callee.object.name === 'Vue' &&
          node.callee.property.name === 'extend'
        ) {
          context.report({ node, messageId: 'noDeprecatedVueExtend' })
        }
      }
    }
  }
}

ASTを解析してVue.extendの呼び出しがあった場合にエラーになるようにしています。

※カスタムルールの追加方法等は以下の記事を参照してください。

madogiwa0124.hatenablog.com

終わりに

ESLintのカスタムルール、お手軽に作れて便利ですね!! 今回のカスタムルールはeslint-plugin-vueにPRを出してみました。

github.com

参考

eslint.vuejs.org