Skip to content

Commit 0bf8db7

Browse files
authored
perf: dynamic imports for certain node: packages (#767)
1 parent 380a373 commit 0bf8db7

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

rsbuild.config.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ export default defineConfig({
2828
},
2929
},
3030
},
31+
externals: {
32+
'node:util': 'node:util',
33+
'node:zlib': 'node:zlib',
34+
},
3135
},
3236
tools: {
3337
htmlPlugin: false,

src/utils.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import type { Readable } from 'node:stream';
2-
import util from 'node:util';
3-
import zlib from 'node:zlib';
42

53
import ow from 'ow';
64
import type { JsonValue, TypedArray } from 'type-fest';
@@ -106,8 +104,7 @@ export function stringifyWebhooksToBase64(webhooks: WebhookUpdateData[]): string
106104
return btoa(String.fromCharCode(...uint8Array));
107105
}
108106

109-
let gzipPromise: ReturnType<(typeof util)['promisify']>;
110-
if (isNode()) gzipPromise = util.promisify(zlib.gzip);
107+
let gzipPromisified: ((arg: string | Buffer<ArrayBufferLike>) => Promise<Buffer>) | undefined;
111108

112109
/**
113110
* Gzip provided value, otherwise returns undefined.
@@ -120,7 +117,13 @@ export async function maybeGzipValue(value: unknown): Promise<Buffer | undefined
120117
// skip it instead of throwing for unsupported types.
121118
const areDataLargeEnough = Buffer.byteLength(value as string) >= MIN_GZIP_BYTES;
122119
if (areDataLargeEnough) {
123-
return gzipPromise(value);
120+
if (!gzipPromisified) {
121+
const { promisify } = await import('node:util');
122+
const { gzip } = await import('node:zlib');
123+
gzipPromisified = promisify(gzip);
124+
}
125+
126+
return gzipPromisified(value);
124127
}
125128

126129
return undefined;

0 commit comments

Comments
 (0)