Skip to content

Minify try-catch-finally syntax #4353

@dgp1130

Description

@dgp1130

Empty catch {} and finally {} blocks should be removed from the bundle. And a try without any catch or finally blocks should also be removed, with its content inlined.

// Input
try {
  console.log('try');
} catch {
  // empty
} finally {
  // empty
}

// Current output
try {
  console.log('try');
} catch {
} finally {
}

// Expected output
console.log('try');

Playground link

This would be useful for situations where error handlers are removed via a --define or other tree shaking mechanism. I ran into it today while trying to do some debug data tracking backed by a --define. I wanted to write:

declare global {
  var isDebug: boolean | undefined; // Set via `--define`.
}

const data: DebugData[] = [];

function doSomething(callback: () => void): void {
  if (isDebug) data.push(getDebugData());
  try {
    callback();
  } finally {
    if (isDebug) data.pop();
  }
}

But this leaves an otherwise-unnecessary try {} and finally {} syntax in production. I can't remove that finally from source as it is necessary for correctness in debug mode, but I'd rather not ship it to production as it's just wasted bytes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions