Skip to content

Proposal for marking functions as pure #1293

@nathancahill

Description

@nathancahill

UPDATED PROPOSAL

UglifyJS2, as of 2.8.0, now supports marking pure with this comment:

/*#__PURE__*/

I propose that Rollup adopt similar behavior to help with tree-shaking.

PREVIOUS PROPOSAL (before UglifyJS release)

I'm proposing adding eslint-style comment annotations to give users more control over tree-shaking:

tree-shaking: pure "Affected expressions will not mark their nodes for inclusion"
tree-shaking: auto "Current behavior"
tree-shaking: side-effects "Affected expressions mark their nodes for inclusion"

Overriding expression marks on a single line:

Greeting.propTypes = {  // rollup-tree-shaking pure
...
}

Overriding expression marks in a block, reverting to auto at the end of the block:

/* rollup-tree-shaking pure */
Greeting.propTypes = {
...
}

Greeting.defaultProps = {
...
};
/* rollup-tree-shaking auto */

Overriding marks for all expressions in a file:

/* rollup-tree-shaking pure */

Marking a line as having side-effects. This expression is marked for inclusion:

documentElement.style.color = 'red';  // rollup-tree-shaking side-effects

Pros

  • The mutable nature of JS makes it impossible to statically analyze common statements, so a lot of potentially pure statements are left on the table when tree-shaking. These annotations allow users to say "I'm not writing maniacal JS" and get drastically smaller bundle sizes.

Cons

  • Build tools that alter code before passing to rollup could shift comments to the wrong line, and apply annotations to the wrong statement(s).
  • Adding program changing logic in comments. There's different camps of thought on this, but generally, comments aren't meant to alter code.
  • Build tools that strip comments could remove annotations if applied in the wrong order.
  • Rollup specific logic. Might make it harder to interop with other build tools.
  • Could become a crutch that prevents rollup tree-shaking bugs from being fixed. If rollup is doing the wrong thing, adding the annotation would allow users to patch it and move on.
  • If users don't understand the risk of overriding rollup's side-effect detection, it could cause unexpected side-effects. Maybe the pure annotation should be unsafe-pure to make the risk clear.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions