Import a module from github

Hi,

I want to use the following module: https://github.com/sebastian-meier/d3.geo2rect/blob/master/build/geo2rect.min.js, I tried https://talk.observablehq.com/t/load-require-import-from-github-pages/296:

geo2rect = import("https://raw.githubusercontent.com/sebastian-meier/d3.geo2rect/master/build/geo2rect.min.js")

and got: SyntaxError: expected expression, got keyword 'import'

and also tried:

geo2rect = require("https://raw.githubusercontent.com/sebastian-meier/d3.geo2rect/master/build/geo2rect.min.js").catch(()=>window.geo2rect)

and got: undefined

Requiring scripts directly from githubusercontent.com is not possible - they set certain HTTP headers that prevent files from being loaded as scripts. You can fetch() other sorts of files and it’ll work, but not scripts, for GitHub’s security reasons.

But you can use RawGit in this case to load files from GitHub and RawGit is much more permissive. Here’s a require that works:

geo2rect = require('https://rawgit.com/sebastian-meier/d3.geo2rect/master/build/geo2rect.js')
2 Likes

It’s possible, but it requires jumping through an extra hoop!

geo2rect = {
  const response = await fetch("https://raw.githubusercontent.com/sebastian-meier/d3.geo2rect/master/build/geo2rect.min.js");
  const blob = await response.blob();
  return require(URL.createObjectURL(blob)).catch(() => window.geo2rect);
}

Live demo: https://beta.observablehq.com/@mbostock/require-from-github

(That said, it would be better to publish this library to npm, and require it from unpkg the normal way.)

2 Likes

Is there a way to do this for a class that uses imports/exports ?