joystick icon indicating copy to clipboard operation
joystick copied to clipboard

Add a helper for dynamically importing browser-only dependencies

Open rglover opened this issue 3 years ago • 2 comments

This has come up more than once. Because Joystick's rendering is isomorphic, if a third-party dependency has a browser-only dependency internally (e.g., navigator) it can trigger build errors.

The fix is to do a dynamic import, but code to do it is clunky:

    onMount: async (component = {}) => {
      if (typeof window !== 'undefined') {
        const WindowDatePicker = (await import('window-date-picker')).default;
        const pickerName = `picker-${component?.props?.name}`;

        window[pickerName] = new WindowDatePicker({
          type: 'DATEHOUR',
          el: `#${pickerName}`,
          toggleEl: `[name="${component?.props?.name}"]`,
          inputEl: `[name="${component?.props?.name}"]`,
        });
      }
    },
  },

Instead, it'd be nice if you could do...

    onMount: async (component = {}) => {
        const WindowDatePicker = await component.import('window-date-picker');
        ...
    },
  },

The idea being that you remove the window check and reaching to get .default boilerplate.

rglover avatar Nov 03 '22 18:11 rglover

Be mindful of named exports. Could just do a import * as PackageName from 'package-name'; style set up to get around this.

rglover avatar Jul 18 '23 03:07 rglover

You can just use the same idea you have in the testing framework for the .load() implementation for this.

rglover avatar Jul 23 '24 21:07 rglover