Skip to content

Conversation

@axetroy
Copy link
Contributor

@axetroy axetroy commented Nov 21, 2024

fix #2468

@github-actions github-actions bot changed the title prefer-global-this: ignore typeof window and typeof self prefer-global-this: ignore typeof window and typeof self Nov 21, 2024
@zanminkian
Copy link
Contributor

Are there any use cases that we have to use typeof window? To detect the runtime environment, we can:

const isBrowser = 'window' in globalThis;
const isNode = 'process' in globalThis;

@sindresorhus
Copy link
Owner

I think it should emit an error, just not auto-fix. Or the check could auto-fix to 'window' in globalThis.

@axetroy
Copy link
Contributor Author

axetroy commented Jan 22, 2025

Auto fix to 'window' in globalThis is not safe. It may break the original code logic.

Should we fix it to typeof globalThis.window?

@axetroy axetroy changed the title prefer-global-this: ignore typeof window and typeof self prefer-global-this: fix auot-fix for typeof window Jan 22, 2025
@sindresorhus
Copy link
Owner

How is it not safe?

@axetroy
Copy link
Contributor Author

axetroy commented Feb 14, 2025

How is it not safe?

Although typeof window === 'undefined' or typeof window !== 'undefined' is a common way for detecting runtime env, there are other ways.

This is in an unfixable case.

- const type = typeof window;
+ const type = 'window' in globalThis;

switch (type) {
	case 'undefined': {
		console.log('Node.js');
		break;
	}

	case 'object': {
        console.log('Browser');
		break;
	}

	default: {
        // unknown
	}
}

I suggest the following solutions:

Option 1. typeof window fix to typeof globalThis.window (I prefer to)

Option 2. Don't provide the fix

Option 3. Detect the case typeof window === 'undefined' and typeof window !== 'undefined'

@sindresorhus
Copy link
Owner

Lets go with 1.

@axetroy
Copy link
Contributor Author

axetroy commented Feb 17, 2025

Lets go with 1.

This is exactly what this PR does.

@fisker Could you review it?

@sindresorhus sindresorhus changed the title prefer-global-this: fix auot-fix for typeof window prefer-global-this: Fix auto-fix for typeof window Feb 17, 2025
@sindresorhus sindresorhus merged commit b95dc12 into sindresorhus:main Feb 17, 2025
17 checks passed
@TrevorBurnham
Copy link

Using typeof globalThis.window instead of typeof window affects bundle sizes in Next.js, and likely other popular JS frameworks. I've spun up a new ticket for discussion: #2605

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

Successfully merging this pull request may close these issues.

prefer-global-this should ignore typeof window === 'undefined'

5 participants