21

Having a JavaScript snippet like:

async function foo() {
  await import('./module.js');
}

and then tidying via the Tidy button, you end up with:

async function foo() {
  await
  import ('./foo.js');
}

which does two things I wouldn't expect:

  • breaking the import onto a new line, and
  • placing a space between import and the opening bracket

Note that, in this usage, this is the dynamic import() function-like, not the static import statement.

4
  • 3
    There's a tidy button in the Stack Snippet editor? That would've saved me a lot of pain while trying to format code. Commented Oct 8, 2020 at 13:10
  • 2
    @GalaxyCat It's... opinionated, and a little wonky sometimes, like in the post. But it's there!
    – zcoop98
    Commented Oct 8, 2020 at 15:02
  • 3
  • Is "JS-Beautify" the official name of the underlying tool? The one referred to in the answer uses "JS Beautifier" (though projects and companies are usually not good at spelling their own main product, even on the main page (three conflicting ones are often seen on the same page)). Or is it meant as a common noun? Commented Aug 21, 2022 at 13:55

2 Answers 2

15

Stack Exchange is using an old version of js-beautify to beautify JS, HTML, and CSS. Dynamic import isn't the only thing the old version gets wrong. It also breaks code when the code contains any of the following:

  • Numeric separators (fixed in new version):

    1_000_000
    

    turns into

    1 _000_000
    
  • Private fields (fixed in new version):

    class X { #foo = 'bar'; }
    

    turns into

    class X {#
      foo = 'bar';
    }
    
  • Logical assignment (fixed in new version):

    a ||= b;
    

    turns into

    a || = b;
    
  • Nullish coalescing (fixed in new version):

    x ?? y
    

    turns into

    x ? ? y
    
  • Optional chaining (fixed in new version):

    x?.y?.z
    

    turns into

    x ? .y ? .z
    

The new version of js-beautify also supports dynamic import:

const code = `
await import('./module.js');   // GOOD

1_000_000                      // GOOD

class X { #foo = 'bar'; }      // GOOD

a ||= b;                       // GOOD

x ?? y                         // GOOD

x?.y?.z                        // GOOD
`;

console.log(js_beautify(code));
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.6/beautify.min.js"></script>

Let's update js-beautify.

6
3

v1.14 improved one of CertainPerformance's bad examples

const code = `
await import('./module.js');   // GOOD

1_000_000                      // GOOD

class X { #foo = 'bar'; }      // GOOD

a ||= b;                       // BAD

x ?? y                         // GOOD

x?.y?.z                        // GOOD
`;

console.log(js_beautify(code));
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.0/beautify.min.js"></script>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .