developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8k stars 361 forks source link

transpiling jsx which includes Array().map or Array.keys #1016

Closed AlbertoPravisano closed 1 year ago

AlbertoPravisano commented 1 year ago

Seems similiar to https://github.com/developit/microbundle/issues/820 I have converted my library from microbundle-crl@0.13.11 to microbundle@0.15.1 and my build and start scripts from

"scripts": {
    "build": "microbundle-crl --no-compress --no-css-modules --no-sourcemap --format modern,cjs",
    "start": "microbundle-crl watch --no-compress --no-css-modules --no-sourcemap --format modern,cjs",
  },

to

"scripts": {
    "build": "microbundle --no-compress --no-css-modules --no-sourcemap --format modern,cjs --jsx React.createElement --jsxFragment React.Fragment",
    "start": "microbundle watch --no-compress --no-css-modules --no-sourcemap --format modern,cjs --jsx React.createElement --jsxFragment React.Fragment",
  },

But i have a problem with javascript Array since [...new Array(nLines).keys()] does not return an array of increasing numbers but returns an empty object [{}] and [...new Array(nLines)].map((_, index) => console.log(index)) prints nothing on console, but both codes works in the browser's dev tools console and in a project builded with react-scripts.

I could use Array.from({ length: nLines }, (_, i) => ( <div key={i} className="line" /> )) which works, but i would prefer to know if i can change some build options to fix it and avoid future similiar occurances (maybe some globals?).

I made a repo with my case https://github.com/AlbertoPravisano/microbundle-test

rschristian commented 1 year ago

This is intentional and a duplicate of #945

In short, we transpile with Babel's loose mode which is somewhat less accurate but produces much smaller output. As such, you'll only see this with your CJS output; Modern is unaffected as spreads are kept.

Edit: To give a better idea of why loose mode is enabled, compare these outputs:

As you can see, while you may need to alter the way you author, there's huge advantages to loose mode. The more correct transpiled code is massive, and that's just for this one, tiny bit of syntax. Imagine what that might do in a larger package.