cheatcode / joystick

A full-stack JavaScript framework for building stable, easy-to-maintain apps and websites.
https://cheatcode.co/joystick
Other
211 stars 11 forks source link

Add a helper for dynamically importing browser-only dependencies #213

Open rglover opened 1 year ago

rglover commented 1 year ago

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 commented 1 year ago

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

rglover commented 2 months ago

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