salesforce / eslint-plugin-lwc

Official ESLint rules for LWC
MIT License
98 stars 32 forks source link

@lwc/lwc/no-restricted-browser-globals-during-ssr doesn't support logical or ternary guards #119

Open seckardt opened 1 year ago

seckardt commented 1 year ago

One annoyance around the @lwc/lwc/no-restricted-browser-globals-during-ssr is related to the fact that it only considers block-level guards as valid like the following:

if (typeof window !== 'undefined') {
    // Client-side
    window.accessClientSideApi();
}

Sometimes it's much more convenient (and absolutely valid) to just add a logical or ternary safe-guard like:

typeof window !== 'undefined' && window.accessClientSideApi();
typeof window !== 'undefined' ? window.accessClientSideApi() : executeServerSideAlternative();
pmdartus commented 1 year ago

@dbleakley What is the recommended approach in LWR to detect whether a component is running on the server or on the client? Is the recommendation to check the presence of the window on the global object or is LWR offering an API specifically for this?

abdulsattar commented 1 year ago

@seckardt is it sufficient if we just support !== (like we do for the if condition)? Do you need

typeof window === 'undefined' || window.accessClientSideApi();
typeof window === 'undefined' ? executeServerSideAlternative() : window.accessClientSideApi();
seckardt commented 1 year ago

I guess as a starting point the !== would be fine. Only problem might be that if someone uses the === or == or != operators and runs into such warnings, it's not obvious why the !== operator works. And you couldn't even help them with a message that restructuring the code would help them get rid of that issue.