From 533fda6d4af1a01f579742418e1cf8abbc0c6785 Mon Sep 17 00:00:00 2001 From: Adam Mockor Date: Fri, 24 Apr 2020 22:28:54 +0200 Subject: [PATCH] guard browser globals on server --- src/scripts/choices.ts | 2 ++ src/scripts/lib/utils.ts | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 238bef8..2b7601e 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -40,6 +40,7 @@ import { generateId, existsInArray, diff, + canUseDom, } from './lib/utils'; import { Options, @@ -54,6 +55,7 @@ import { defaultState } from './reducers'; /** @see {@link http://browserhacks.com/#hack-acea075d0ac6954f275a70023906050c} */ const IS_IE11 = + canUseDom && '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style; diff --git a/src/scripts/lib/utils.ts b/src/scripts/lib/utils.ts index 1508e09..bdaea5d 100644 --- a/src/scripts/lib/utils.ts +++ b/src/scripts/lib/utils.ts @@ -1,5 +1,11 @@ import { EventMap, Choice } from '../interfaces'; +export const canUseDom = !!( + typeof window !== 'undefined' && + window.document && + window.document.createElement +); + /* eslint-disable @typescript-eslint/no-explicit-any */ export const getRandomNumber = (min: number, max: number): number => @@ -97,6 +103,14 @@ export const sanitise = (value: T | string): T | string => { }; export const strToEl = ((): ((str: string) => Element) => { + // do not run this in non-browser environment + if (!canUseDom) { + // eslint-disable-next-line @typescript-eslint/ban-ts-ignore + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-empty-function + return (): void => {}; + } + const tmpEl = document.createElement('div'); return (str): Element => {