Skip to content

Instantly share code, notes, and snippets.

@o-az
Last active April 23, 2023 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save o-az/e8ed1e89fde52af306099ed28e297cae to your computer and use it in GitHub Desktop.
Save o-az/e8ed1e89fde52af306099ed28e297cae to your computer and use it in GitHub Desktop.
https imports in Node.js (aka 'import from url')
import { get } from "node:https";
export function resolve(specifier, context, nextResolve) {
const { parentURL = null } = context;
// Normally Node.js would error on specifiers starting with 'https://', so
// this hook intercepts them and converts them into absolute URLs to be
// passed along to the later hooks below.
if (specifier.startsWith("https://")) {
return {
shortCircuit: true,
url: specifier,
};
} else if (parentURL && parentURL.startsWith("https://")) {
return {
shortCircuit: true,
url: new URL(specifier, parentURL).href,
};
}
// Let Node.js handle all other specifiers.
return nextResolve(specifier);
}
export function load(url, context, nextLoad) {
// For JavaScript to be loaded over the network, we need to fetch and
// return it.
if (url.startsWith("https://")) {
return new Promise((resolve, reject) => {
get(url, (res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () =>
resolve({
// This example assumes all network-provided JavaScript is ES module
// code.
format: "module",
shortCircuit: true,
source: data,
})
);
}).on("error", (err) => reject(err));
});
}
// Let Node.js handle all other URLs.
return nextLoad(url);
}
import { example } from "https://gist.githubusercontent.com/o-az/e8ed1e89fde52af306099ed28e297cae/raw/51a1d68f54ba0718c2ab72a52b97f13cf613563f/sample.js";
console.log(example());

https imports

Node.js requires a custom https-loader: https://nodejs.org/api/esm.html#https-loader

The loader (https-loader.js):

The sample file (sample.js):

export const example = () => ({ foo: "bar" });

The test snippet (index.js):

import { example } from "https://gist.githubusercontent.com/o-az/e8ed1e89fde52af306099ed28e297cae/raw/51a1d68f54ba0718c2ab72a52b97f13cf613563f/sample.js";

console.log(example());

The command:

Runtime Command
Node.js node --experimental-loader='./https-loader.js' index.js
Deno deno run --allow-net index.js
;(() => ({ foo: console.log('bar') }))()
export const example = () => ({ foo: "bar" });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment