Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Annotate" exported object to fix named / namespace imports of our API in Node ESM #57133

Merged
merged 20 commits into from
Mar 4, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use require instead of dynamic import
  • Loading branch information
jakebailey committed Jan 24, 2024
commit e0d8ea5bb22402a62d5d848c9a23f9ab9e2f7a3f
17 changes: 10 additions & 7 deletions Herebyfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import {
import {
task,
} from "hereby";
import path from "path";
import {
pathToFileURL,
} from "url";
createRequire,
} from "module";
import path from "path";

import {
localizationDirectories,
Expand Down Expand Up @@ -176,6 +176,8 @@ async function runDtsBundler(entrypoint, output) {
]);
}

const requireFn = createRequire(import.meta.url);

/**
* @param {string} entrypoint
* @param {string} outfile
Expand Down Expand Up @@ -230,7 +232,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
options.define = { [require]: fakeName };
options.plugins = [
{
name: "fix-require",
name: "post-process",
setup: build => {
build.onEnd(async () => {
let contents = await fs.promises.readFile(outfile, "utf-8");
Expand All @@ -249,9 +251,10 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
// esbuild's metafile option does not show exports...
// https://github.com/evanw/esbuild/issues/3110
// https://github.com/evanw/esbuild/issues/3281
const importUrl = pathToFileURL(outfile).toString();
const obj = await import(importUrl);
const names = Object.keys(obj.default);

// Using createRequire here is emperically faster than await import.
const obj = requireFn(outfile);
const names = Object.keys(obj);
const fakeExport = ` 0 && (module.exports = {\n${names.map(name => ` ${name},\n`).join("")} });`;
contents = contents.replace("module.exports = ts;", `module.exports = ts;\n${fakeExport}`);
await fs.promises.writeFile(outfile, contents);
Expand Down