Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect error reporting from prefer-global-this rule #2489

Closed
charles4221 opened this issue Oct 27, 2024 · 3 comments
Closed

Incorrect error reporting from prefer-global-this rule #2489

charles4221 opened this issue Oct 27, 2024 · 3 comments

Comments

@charles4221
Copy link

I just upgraded my version of the plugin to 56.0.0 and started getting lint errors for the prefer-global-this rule on code like this:

export function detectPrefersDarkMode() {
  return (
    typeof window !== 'undefined' &&
    window.matchMedia('(prefers-color-scheme: dark)').matches
  );
}

Shouldn't this type of usage be excluded from this rule since globalThis.matchMedia will crash with a TypeError: globalThis.matchMedia is not a function?

The above example is also a common use case in apps that run on both server and client, to check that the browser environment exists before running browser-specific code. globalThis isn't going to work for those use cases.

@sindresorhus
Copy link
Owner

This is a faulty check. You can no longer make this assumption, regardless of this rule. The correct way is to test the individual functions. I think this rule is doing you a favor by leading you to a better pattern.

export function detectPrefersDarkMode() {
  return globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false
}

@fregante

This comment was marked as outdated.

@fregante fregante closed this as not planned Won't fix, can't repro, duplicate, stale Oct 30, 2024
@fregante
Copy link
Collaborator

Duplicate of #2468

@fregante fregante marked this as a duplicate of #2468 Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants