Matthias
Matthias

Reputation: 15385

Eslint rule for banning usage of `function.name` and `constructor.name`?

Is there an eslint rule that forbids the use of the name property of a function?

When you minify code it typically mangles a function's name. So in development, myFunc.name will be 'myFunc', but in production it will be something like 'a'. This is a development footgun and I would like to prevent this.

eslint-plugin-ban only applies to call expressions, but I want something that applies to accessing the property (MemberExpression).

Upvotes: 8

Views: 1247

Answers (1)

Stanislav Berkov
Stanislav Berkov

Reputation: 6287

There is a bit different eslint plugin https://runebook.dev/en/docs/eslint/rules/no-restricted-syntax

I use it to warn constructor.name usage having the following eslint rule setting (yaml syntax):

  "no-restricted-syntax":
    - warn
    - selector: MemberExpression[object.property.name='constructor'][property.name='name']
      message: "'constructor.name' is not reliable (can become 'E', 'P' and etc.) after standard angular production build (JavaScriptOptimizer)."

PS: there is a tool https://estools.github.io/esquery/ for debugging ES AST queries that can be used for no-restricted-syntax

UPDATE: There is even more convenient tool to debug the syntax rules: https://typescript-eslint.io/play/#ts=4.7.2&sourceType=module&showAST=es

Upvotes: 7

Related Questions