Alex Alexiuc
Alex Alexiuc

Reputation: 83

esbuild not tree-shaking aws-sdk comand injected client

When bundling typescript code with esBuild, having this configuration:

const buildOpts: BuildOptions = {
  target: 'es2020',
  format: 'esm',
  mainFields: ['module', 'main'],
  metafile: true,
  treeShaking: true,
};

moduleResolution: Bundler in tsconfig

With this sample code

import { S3Client } from '@aws-sdk/client-s3';

const s3Client = new S3Client();

console.log(s3Client.config);

In the resulting bundle, I would expect only to have S3Client-related code, but it also contains all S3 commands, because of command injection library does.

I would expect that setting mainFields to module, main, would prevent esBuild from adding to the bundle files that are not imported, as I do not have import { S3 } from '@aws-sdk/client-s3';

Am I missing something in the setup, or it is just how esBuild works?

Upvotes: 1

Views: 119

Answers (1)

spaceemotion
spaceemotion

Reputation: 1546

If you import the S3 client directly, you no longer include all commands directly:

import type { S3Client} from '@aws-sdk/client-s3';

// @ts-expect-error Types are missing for the specific import
import { S3Client as RawS3Client } from '@aws-sdk/client-s3/dist-es/S3Client.js';


export const s3: S3Client = new RawS3Client();

In my tests, this brought the bundle size from 198kb down to 42kb.

Upvotes: 0

Related Questions