Implement tree-shaking in typescript

Viewed 566

I'm building a re-usable telemetry library using TypeScript and OpenTelemetry. I'm trying to see how I can implement tree-shaking such that consumer can import only the modules they need and not everything and so they can reduce the overall bundle size. The project structure looks like this,

lib
|
|__ trace
|    |____ TraceClass.ts
|    |____ index.ts
|
|__ metrics
|    |____ MetricClass.ts
|    |____ index.ts
|
|__ logs
|    |____ LogClass.ts
|    |____ index.ts
|
|__ index.ts

I've three major modules "trace", "log" and "metrics" as separate folders. As you see each of the module has it's own "index.ts" file and there is a root "index.ts" file. Let's say if the root "index.ts" file exports all the things like of the sub-modules.

root index.ts

export * from './trace';
export * from './metrics';
export * from './logs';

Let's say the consumer import the TraceClass from the root file as below,

import { TraceClass } from 'mytelemetrylib';

Does the above code imports all the modules in their code?

or they have to do something like this?

import { TraceClass } from 'mytelemetrylib/trace';
1 Answers

If in the index.ts of the trace folder:

lib
|
|__ trace
|    |____ TraceClass.ts
|    |____ index.ts

You've exported everything (e.g export * from './TraceClass';) and within the TraceClass.ts the class is also exported (e.g export class TraceClass) then import have access to all of the things explicitly exported (e.g import { TraceClass } from 'mytelemetrylib'; will be enough).

Additionally, you could "namespace" the exports for code clarity. For example:

export * as Trace from './trace';
export * as Metrics from './metrics';
export * as Logs from './logs';

The consumer could then import:

import { Trace, Metrics, Logs } from 'mytelemetrylib';

And use them with:

Trace.TraceClass // or any other explicitly exported trace related functionality.
Related