Pricing Blog

Best practice for importing script for a package

  • quietrocket-1366493442166751394

    QuietRocket

    3 months ago

    Hi! I am making a community package for Convex by wrapping Convex's plain JavaScript library (inspired by their Svelte package). The documentation for the library can be found here: https://docs.convex.dev/quickstart/script-tag

    According to the docs, they recommend adding a script tag to unpkghttps://unpkg.com/convex@1.3.1/dist/browser.bundle.js as such:
    <!doctype html>
    <script src="https://unpkg.com/convex@1.3.1/dist/browser.bundle.js"></script>
    <script>
    const CONVEX_URL = "CONVEX_URL_GOES_HERE";
    const client = new convex.ConvexClient(CONVEX_URL);
    client.onUpdate("tasks:get", {}, (tasks) =>
    console.log(tasks.map((task) => task.text)),
    );
    </script>

    This works in Nord by modifying the page external resources, but the problem is as a package, I don't think it's very reasonable for the end user to have to add the script every page manually.

    I tried importing an ESM variant through JSDelivr via a Nord action, but the imported module seems to be empty: https://cdn.jsdelivr.net/npm/convex@1.23.0/+esm

    Honestly I would prefer going about an import() the ESM way, but what's the right module to import? The import I'm interested in is convex/browser (which contains ConvexClient, for example).

    Thanks 🙂
    1
  • lucasg-1366494807215702157

    Lucas G

    3 months ago

    Yeah it's preferrable to use custom actions to load external resources rather than header.
    Typically it's something like
    const { thing } = await import('https://cdn.jsdelivr.net/npm/[THING]/+esm');
  • Actual 'thing' depends on the package
  • quietrocket-1366495064641241100

    QuietRocket

    3 months ago

    Yes I tried that, but it's empty.
  • Tod-1366495066172166196

    Tod

    3 months ago

    Great job @QuietRocket! Your contribution to the Nordcraft Community just made you advance to Community Level 2! 🌲
  • lucasg-1366495199035134103

    Lucas G

    3 months ago

    May not even need to assign it. I've done plain await import (); and that works as well
    👀1
  • Again, it depends on the package and how you're using it
  • quietrocket-1366502109750628384

    QuietRocket

    3 months ago

    Ok this works!
    const convex = await import("https://cdn.jsdelivr.net/npm/convex@1.23.0/dist/esm/browser/index.js/+esm")
    The trouble was finding the right path.
    I found it by going to https://cdn.jsdelivr.net/npm/convex@1.23.0/ then navigating to dist/esm/browser/index.js.
    Then just appending /+esm made it compatible. Thanks!
    1