Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - How can I detect name collision of local classes with global ones in JS or TS using ESLint?

In JavaScript, you can define a class with a name like Node or Attr. I think it might lead a confusion, as there is also a global constructor function with the same names. I believe linting is ESLint's job, but I couldn't figure out how to configure it to detect it. Neither no-shadow nor no-redeclare seems not working for this kind of redeclaration or shadowing. typescript-eslint couldn't detect it either.

Is there a way to prevent shadowing of global classes?

Edit: no-shadow with { builtinGlobals: true } doesn't do a trick. It works only for names like Object or undefined.

question from:https://stackoverflow.com/questions/66046537/how-can-i-detect-name-collision-of-local-classes-with-global-ones-in-js-or-ts-us

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I mentioned in the comments, this can be achieved by using the no-shadow rule. By default, the rule does not check the built-in types (e.g. window, Node or Attr), but it can be configured to do so by setting the option builtinGlobals to true, like this:

no-shadow: ["error", { "builtinGlobals": true }]

This now tells ESLint to check if any variables shadows any name that is available in the global scope - but you have to configure which ones are actually available, since ESLint does not know that by itself. You can do that by setting the correct environments through the env configuration:

"env": { 
    "browser": true
}

I configured a small example in the ESLint Playground Demo to showcase this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...