Skip to content

Instantly share code, notes, and snippets.

@jacob-ebey
Created June 5, 2022 21:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacob-ebey/137cdc777406874472e56f22499130d9 to your computer and use it in GitHub Desktop.
Save jacob-ebey/137cdc777406874472e56f22499130d9 to your computer and use it in GitHub Desktop.
Node.js dynamic import cache buster
import { readFile } from "fs/promises";
import { createRequire } from "module";
import * as URL from "url";
import { readConfig } from "./config.mjs";
let require = createRequire(import.meta.url);
let config = await readConfig(process.cwd(), "development");
let outputFile = URL.pathToFileURL(config.serverBuildPath);
export async function load(url, context, defaultLoad) {
let baseUrl = url.split("?", 1)[0];
if (baseUrl.endsWith(outputFile)) {
if (context.format === "module") {
return {
format: "module",
source: await readFile(new URL.URL(baseUrl)),
};
} else {
let buildPath = require.resolve(config.serverBuildPath);
delete require.cache[buildPath];
}
}
return defaultLoad(url, context, defaultLoad);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment