developit / microbundle

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

fix: disable tree-shaking via PURE annotations when compression is disabled #1012

Open quantizor opened 1 year ago

quantizor commented 1 year ago

When building a library, "pure" comments are often added to various bits and pieces to ensure tree-shaking works properly in the destination bundle. Compression via terser will automatically drop these hints in some cases, so disabling compression serves the purpose of leaving total minification up to the destination bundler.

At the moment, rollup takes these pure comments into account as well when bundling which can lead to early-dropping of statements that are meant to be dropped later in the destination bundler. We should disable "pure" comment-related treeshaking in microbundle when compression is turned off to ensure this use case works as expected.

For example, here's a use case which involves setting displayName on a component in a way that if the component is tree-shaken, the displayName goes away as well:

export const Foo = (props) => <div {...props} />

/*#​__PURE__*/Object.assign(Foo, { displayName: 'Foo' });
changeset-bot[bot] commented 1 year ago

⚠️ No Changeset found

Latest commit: 4b968bace44f95551a734e8b85d05e1cb31b9f68

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

developit commented 1 year ago

@probablyup I'm curious how you ended up with that code from the snippet - normally I'd expect the pure annotation to apply to the Object.assign property access, not the function call:

export const Foo = (props) => <div {...props} />

(/*#​__PURE__*/ Object.assign)(Foo, { displayName: 'Foo' });

Is the annotation something you're adding? Or a Babel plugin?