LoginSignup
2
3

ESLint で Date オブジェクトの使用を禁止する

Posted at

new Date()Date.parse() だけを禁止したい場合は amzn/eslint-plugin-no-date-parsing などが使えますが、 Date オブジェクトに生えている全てのメソッドも禁止したい場合は、以下のようなルールを書くことで実現できます。
ESLint Flat Config を使う場合は適宜読み替えてください。)

eslintrc.json
{
  "rules": {
    "no-restricted-syntax": [
      "error",
      {
        "selector": "NewExpression[callee.name='Date']",
        "message": "Use dayjs instead."
      },
      {
        "selector": "CallExpression[callee.object.name='Date']",
        "message": "Use dayjs instead."
      }
    ]
  }
}

no-restricted-syntax というルールを使うことで実現しています。
こちらの記事に詳しい使い方が書いてあるので詳細は省きますが、このルールを使うことで特定の構文を禁止できるようになります。
(余談ですが http://estools.github.io/esquery/ は中々楽しいので、是非触ってみてください。)

また私のチームでは Day.js を使っているので、メッセージではそちらを使うよう促しています。

誰かの参考になれば幸いです。
(もっと良いやり方をご存知の方がいれば、コメントにてお教えください。)

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3