A "module loader" for UMD modules from unpkg

So… as soon as I start writing JS I kind of want all of npm available to me. Here’s my first try at that. It’s a real mess of a hack but its so useful and neat that it felt worth sharing anyway:

var need = async package => {
  const fm = FileManager.local()
  try {
    fm.createDirectory("/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/need/", false)
  } catch (exists) {}
  const path = `/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/need/${package}.hidejs`
  if (!fm.fileExists(path)) {
    const unpkg = new Request(`https://unpkg.com/${package}`)
    const code = await unpkg.load()
    fm.write(path, code)
  }
  return eval(fm.readString(path))
}

put that in a script named need and then you use it like

eval(FileManager.local().readString("/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/need.js"))

await need("lodash")

console.log(_.times(12, Date.now))

Is there a nicer alternative to that first line to import a local script? I did it like this because I wanted a copy and paste-able one liner. Maybe the app will get something nicer in the future for that?

I also saw that an import() function is available and it gives me error messages that sound like it wants to load ES6 modules but I couldn’t figure anything out. Having the ability to use that to load modules from urls (unpkg ?module feature) as well as loading other scripts as modules would be amazing though It might be against app review?

4 Likes

I tried to create an ES6 module but I don’t think Safari support native modules yet. This is a nice solution until a proper way to import other files is known. I’m going to use this for now to include a common library of JS utility functions. Thanks for posting this.

Safari does actually support them, and I think this is why the import function is there, as its part of JSC. But I had no idea where to load them from, since only URLs/paths work as module specifiers and I think reading from file or web urls like that is not implemented.