devrelm / resize-observer

Other
98 stars 12 forks source link

ESLint-Error: 'ResizeObserver' is already declared in the upper scope (no-shadow) #18

Closed Andy-QT closed 5 years ago

Andy-QT commented 5 years ago

Import in file.js: import {ResizeObserver} from 'resize-observer';

devrelm commented 5 years ago

Interesting. I'm not sure how useful that lint-rule is in this case, though. Shadowing is usually only bad for the same reason as not having curly brackets around a single-line if statement: it can lead to developers becoming complacent and missing errors:

// GOOD
if (something) {
  doSomething();
}

// OK (but not a good idea)
if (something)
  doSomething();

// NOT OK (but is likely to happen if you don't use curlies)
if (something)
  doSomething();
  doSomethingElse(); // this is always called, even though you probably didn't mean to

Similarly:

// OK
import { ResizeObserver } from 'resize-observer';
const ro = new ResizeObserver(callback);

// NOT OK (in different file)
const ro = new ResizeObserver(callback);

In the first instance, ResizeObserver will always be the one imported from resize-observer, since that's what's in the most recent scope. (Of course, now that I've said this, someone will point out some obscure section of the ES language spec saying that this isn't always true.)

In the second instance, ResizeObserver will not always exist, depending on the browser. If you get in the habit of importing ResizeObserver as in the first case, then you might end up forgetting to import it in some case, and your linter won't complain since it's in the global scope. Then you'll be left with some weird errors on one page in your site in certain old browsers referring to something that you swore you added a polyfill for.


So, now that I've told you a bunch of stuff that you probably already knew: here's a few options for I'd go about fixing it. You'd only have to do one of the three to fix your issue:

  1. If possible, update your linter rules to ignore shadowing ResizeObserver. It looks like you can do this with the builtinGlobals or allow options on the no-shadow rule.
  2. Alias the import: import { ResizeObserver as RO } from 'resize-observer';
  3. Install resize-observer as a polyfill, then always use the global ResizeObserver instead of importing each time.

Please post back if these help, or if you have other ideas/solutions.

Andy-QT commented 5 years ago

@devrelm I used the (2.) Alias method and it works as expected. The first method (1.) would also work, it depends on the personal preference.

Thank you for all your tips and the description.

devrelm commented 5 years ago

You're welcome, Andy. I'll close this issue, but feel free to reply again if there's still an issue.