Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unfold nested blocks when minifySyntax is enabled #3158

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

sapphi-red
Copy link
Contributor

Summary

For an input like this,

function fn1 () {
  if (true) {
    let a = 'foo';
    console.log(a);
    console.log(a);
  }
}

esbuild currently outputs

function fn1() {
  {
    let a = "foo";
    console.log(a), console.log(a);
  }
}

. But this can be minified to

function fn1() {
  let a = "foo";
  console.log(a), console.log(a);
}

. This PR implements removing these braces.

Supported cases

function fn1 () {
  if (true) {
    let a = 'foo';
    console.log(a);
    console.log(a);
  }
}

const fn2 = () => {
  if (true) {
    let a = 'foo';
    console.log(a);
    console.log(a);
  }
};

const fn3 = function () {
  if (true) {
    let a = 'foo';
    console.log(a);
    console.log(a);
  }
};

const obj = {
  method2() {
    if (true) {
      let a = 'foo';
      console.log(a);
      console.log(a);
    }
  }
};

class Foo {
  static {
    if (true) {
      let a = 'foo';
      console.log(a);
      console.log(a);
    }
  }
}

current esbuild try

Other benefits

When this code is passed to Rollup,

export function fn1 () {
  {
    let a = 'foo';
    console.log(a);
    console.log(a);
  }
}

Rollup outputs

export function fn1() {
  {
    let a = "foo";
    console.log(a), console.log(a);
  }
}

(Rollup REPL).

When this output is passed to esbuild, esbuild currently outputs the braces as-is (current esbuild try).

This PR works for these cases, too.

Related information

A block inside if / for/while seems to be already supported: esbuild try

terser doesn't support this: terser/terser#1363

@ghiscoding
Copy link

@evanw any chance this could get reviewed (even if there's now conflicts)? This seems like a suboptimal output and @sapphi-red is main contributor on the Vite project. Thank you both for all these great projects :)

@hyf0
Copy link

hyf0 commented Aug 7, 2023

What will happen for input?

function fn1 () {
  let a = 'foo_outer';
  if (true) {
    let a = 'foo';
    console.log(a);
    console.log(a);
  }
  console.log(a)
}

@sapphi-red
Copy link
Contributor Author

This PR won't change the output for that case. It only affects when the block has a single block inside it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants