Skip to content

Commit 4f1c797

Browse files
committed
refactor: add isServer to be compatible with node env
1 parent ec7dc30 commit 4f1c797

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

src/__tests__/utils-node.test.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* @jest-environment node
3+
*/
4+
5+
import { isServer } from '../core/utils';
6+
7+
describe('utils-node-env', () => {
8+
test('isServer should work', async () => {
9+
expect(isServer).toBe(true);
10+
});
11+
});

src/core/utils/index.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@ export const isFunction = (fn: unknown): fn is Function =>
1717

1818
export const isNil = (val: unknown) => val === null || val === undefined;
1919

20+
export const isServer = typeof window === 'undefined';
21+
2022
export const isDocumentVisibility = () =>
21-
window?.document?.visibilityState === 'visible';
23+
!isServer && window?.document?.visibilityState === 'visible';
2224

23-
export const isOnline = () => window?.navigator?.onLine ?? true;
25+
export const isOnline = () => (!isServer && window?.navigator?.onLine) ?? true;
2426

2527
export const unRefObject = <T extends RefObject>(val: T) => {
2628
const obj = {};

src/core/utils/listener.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isDocumentVisibility } from './index';
1+
import { isDocumentVisibility, isServer } from './index';
22

33
type EventFunc = () => void;
44
type ListenersSet = Set<EventFunc>;
@@ -40,7 +40,7 @@ const observer = (listeners: ListenersSet) => {
4040
};
4141

4242
/* istanbul ignore else */
43-
if (window?.addEventListener) {
43+
if (!isServer && window?.addEventListener) {
4444
window.addEventListener(
4545
'visibilitychange',
4646
() => {

0 commit comments

Comments
 (0)