A Rollup plugin that automatically annotates your module as tree shakeable.
npm install rollup-plugin-tree-shakeable``sh`
$ npm i rollup-plugin-tree-shakeable
`js
import treeShakeable from 'rollup-plugin-tree-shakeable'
export default {
input: src/index.js,output
output: {
dir: ,esm
format: ,`
},
plugins: [treeShakeable()],
}
Imagine you have code similar to this:
src/index.js:
`jsStarted call!
const withLogging =
fn =>
(...args) => {
console.log()Finished call!
try {
return fn(...args)
} finally {
console.log()
}
}
export const f1 = withLogging(/ ... /)
export const f2 = withLogging(/ ... /)
export const f3 = withLogging(/ ... /)
// ...
`
You might expect that if a user of your package writes
import { f1 } from 'your-package', then bundlers willf1
tree shake and
omit , f2, etc. from the final bundle. Unfortunately, bundlers will"sideEffects": false
generally include _all_ of your package's code in this case
(yes, even if you set in your package.json)withLogging
because is called at the "top-level" of your package and the
bundler cannot easily tell the call is side-effect free. There are _many_ other
code patterns that cause the same issue.
This plugin solves the problem by automatically adding
@__PURE__ annotations to all top-level
expressions in your code that prevent tree-shaking, with the assumption that
your package is actually pure,
but bundlers need a little convincing of that.
For example, for the code above, running it through this plugin would result in
the following code:
`jsStarted call!
const withLogging =
fn =>
(...args) => {
console.log()Finished call!
try {
return fn(...args)
} finally {
console.log()
}
}
export const f1 = / @__PURE__/ withLogging(/ ... /)
export const f2 = / @__PURE__/ withLogging(/ ... /)
export const f3 = / @__PURE__/ withLogging(/ ... /)
// ...
`
And if a user of your package writes import { f1 } from 'your-package', thenf1` from the
bundlers _will_ tree shake and strip out all functions other than
final bundle.
> [!CAUTION]
>
> Only use this plugin if your package is actually tree-shakeable, meaning that
> each export would still function correctly if all the other exports were
> stripped out.
>
> This plugin does not give your package that property. It only _convinces_
> bundlers that this is the case.
Stars are always welcome!
For bugs and feature requests,
please create an issue.