Skip to content

Commit 77231a2

Browse files
committed
fix: Suppress node 23 warnings about require-ing ESM
1 parent 29ceeb5 commit 77231a2

File tree

1 file changed

+31
-1
lines changed
  • packages/devtools-proxy-support/src

1 file changed

+31
-1
lines changed

packages/devtools-proxy-support/src/fetch.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@ async function importNodeFetch(): Promise<typeof fetch> {
1212
// Node-fetch is an ESM module from 3.x
1313
// Importing ESM modules to CommonJS is possible with a dynamic import.
1414
// However, once this is transpiled with TS, `await import()` changes to `require()`, which fails to load
15-
// the package at runtime.
15+
// the package at runtime for Node < 23.
1616
// The alternative, to transpile with "moduleResolution": "NodeNext", is not always feasible.
1717
// Use this function to safely import the node-fetch package
1818
let module: typeof fetch | { default: typeof fetch };
1919
try {
20+
suppressExperimentalWarningsIfNecessary();
2021
module = await import('node-fetch');
2122
} catch (err: unknown) {
2223
if (
@@ -37,6 +38,35 @@ async function importNodeFetch(): Promise<typeof fetch> {
3738

3839
return typeof module === 'function' ? module : module.default;
3940
}
41+
42+
let warningsSuppressed = false;
43+
44+
// In Node.js 23 require()ing ESM modules will work, but emit an experimental warning like
45+
// CommonJS module ABC is loading ES Module XYZ using require().
46+
// This function suppresses experimental warnings to avoid those leaking into end users' output.
47+
function suppressExperimentalWarningsIfNecessary() {
48+
const nodeMajorVersion = process.versions.node.split('.').map(Number)[0];
49+
if (nodeMajorVersion >= 23 && !warningsSuppressed) {
50+
const originalEmit = process.emitWarning;
51+
process.emitWarning = (warning, ...args: any[]): void => {
52+
if (args[0] === 'ExperimentalWarning') {
53+
return;
54+
}
55+
56+
if (
57+
typeof args[0] === 'object' &&
58+
args[0].type === 'ExperimentalWarning'
59+
) {
60+
return;
61+
}
62+
63+
originalEmit(warning, ...args);
64+
};
65+
66+
warningsSuppressed = true;
67+
}
68+
}
69+
4070
let cachedFetch: Promise<typeof fetch> | undefined;
4171

4272
export type { Request, Response, RequestInfo, RequestInit };

0 commit comments

Comments
 (0)