Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement --treeshake.propertyReadSideEffects=always to handle getters with side effects #3985

Merged
merged 1 commit into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/999-big-list-of-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -1353,7 +1353,7 @@ Default: `false`
If this option is provided, bundling will not fail if bindings are imported from a file that does not define these bindings. Instead, new variables will be created for these bindings with the value `undefined`.

#### treeshake
Type: `boolean | { annotations?: boolean, moduleSideEffects?: ModuleSideEffectsOption, propertyReadSideEffects?: boolean, tryCatchDeoptimization?: boolean, unknownGlobalSideEffects?: boolean }`<br>
Type: `boolean | { annotations?: boolean, moduleSideEffects?: ModuleSideEffectsOption, propertyReadSideEffects?: boolean | 'always', tryCatchDeoptimization?: boolean, unknownGlobalSideEffects?: boolean }`<br>
CLI: `--treeshake`/`--no-treeshake`<br>
Default: `true`

Expand Down Expand Up @@ -1467,12 +1467,16 @@ console.log(foo);
Note that despite the name, this option does not "add" side effects to modules that do not have side effects. If it is important that e.g. an empty module is "included" in the bundle because you need this for dependency tracking, the plugin interface allows you to designate modules as being excluded from tree-shaking via the [`resolveId`](guide/en/#resolveid), [`load`](guide/en/#load) or [`transform`](guide/en/#transform) hook.

**treeshake.propertyReadSideEffects**<br>
Type: `boolean`<br>
Type: `boolean | 'always'`<br>
CLI: `--treeshake.propertyReadSideEffects`/`--no-treeshake.propertyReadSideEffects`<br>
Default: `true`

If `true`, retain unused property reads that Rollup can determine to have side-effects. This includes accessing properties of `null` or `undefined` or triggering explicit getters via property access. Note that this does not cover destructuring assignment or getters on objects passed as function parameters.

If `false`, assume reading a property of an object never has side effects. Depending on your code, disabling this option can significantly reduce bundle size but can potentially break functionality if you rely on getters or errors from illegal property access.

If `'always'`, assume all member property accesses, including destructuring, have side effects. This setting is recommended for code relying on getters with side effects. It typically results in larger bundle size, but smaller than disabling `treeshake` altogether.

```javascript
// Will be removed if treeshake.propertyReadSideEffects === false
const foo = {
Expand Down
5 changes: 3 additions & 2 deletions src/ast/nodes/MemberExpression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,12 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE
}

hasEffects(context: HasEffectsContext): boolean {
const propertyReadSideEffects = (this.context.options.treeshake as NormalizedTreeshakingOptions).propertyReadSideEffects;
return (
propertyReadSideEffects === 'always' ||
this.property.hasEffects(context) ||
this.object.hasEffects(context) ||
((this.context.options.treeshake as NormalizedTreeshakingOptions).propertyReadSideEffects &&
this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!], context))
(propertyReadSideEffects && this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!], context))
);
}

Expand Down
6 changes: 5 additions & 1 deletion src/ast/nodes/Property.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import MagicString from 'magic-string';
import { NormalizedTreeshakingOptions } from '../../rollup/types';
import { RenderOptions } from '../../utils/renderHelpers';
import { CallOptions, NO_ARGS } from '../CallOptions';
import { DeoptimizableEntity } from '../DeoptimizableEntity';
Expand Down Expand Up @@ -84,7 +85,10 @@ export default class Property extends NodeBase implements DeoptimizableEntity, P
}

hasEffects(context: HasEffectsContext): boolean {
return this.key.hasEffects(context) || this.value.hasEffects(context);
const propertyReadSideEffects = (this.context.options.treeshake as NormalizedTreeshakingOptions).propertyReadSideEffects;
return this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always' ||
this.key.hasEffects(context) ||
this.value.hasEffects(context);
}

hasEffectsWhenAccessedAtPath(path: ObjectPath, context: HasEffectsContext): boolean {
Expand Down
4 changes: 2 additions & 2 deletions src/rollup/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ export interface OutputPlugin extends Partial<OutputPluginHooks>, Partial<Output
export interface TreeshakingOptions {
annotations?: boolean;
moduleSideEffects?: ModuleSideEffectsOption;
propertyReadSideEffects?: boolean;
propertyReadSideEffects?: boolean | 'always';
/** @deprecated Use `moduleSideEffects` instead */
pureExternalModules?: PureModulesOption;
tryCatchDeoptimization?: boolean;
Expand All @@ -487,7 +487,7 @@ export interface TreeshakingOptions {
export interface NormalizedTreeshakingOptions {
annotations: boolean;
moduleSideEffects: HasModuleSideEffects;
propertyReadSideEffects: boolean;
propertyReadSideEffects: boolean | 'always';
tryCatchDeoptimization: boolean;
unknownGlobalSideEffects: boolean;
}
Expand Down
6 changes: 4 additions & 2 deletions src/utils/options/normalizeInputOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ const getTreeshake = (
| {
annotations: boolean;
moduleSideEffects: HasModuleSideEffects;
propertyReadSideEffects: boolean;
propertyReadSideEffects: boolean | 'always';
tryCatchDeoptimization: boolean;
unknownGlobalSideEffects: boolean;
} => {
Expand All @@ -261,7 +261,9 @@ const getTreeshake = (
configTreeshake.pureExternalModules,
warn
),
propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
propertyReadSideEffects:
configTreeshake.propertyReadSideEffects === 'always' && 'always' ||
configTreeshake.propertyReadSideEffects !== false,
tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
};
Expand Down
4 changes: 4 additions & 0 deletions test/cli/samples/propertyReadSideEffects-always/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
description: 'verify property accesses are retained for getters with side effects',
command: `rollup main.js --validate --treeshake.propertyReadSideEffects=always`
};
17 changes: 17 additions & 0 deletions test/cli/samples/propertyReadSideEffects-always/_expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class C {
get x() {
console.log(`side effect ${++count}`);
return 42
}
}
let count = 0;
const obj = new C;
console.log(obj.x);

// these statements should be retained
if (obj.x) {
obj["x"];
const {x} = obj;
}
let x;
({x} = obj);
21 changes: 21 additions & 0 deletions test/cli/samples/propertyReadSideEffects-always/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class C {
get x() {
console.log(`side effect ${++count}`)
return 42
}
}
let count = 0
const obj = new C
console.log(obj.x)

// these statements should be retained
if (obj.x) {
obj["x"]
const {x} = obj
}
let x
({x} = obj)

// demonstrate that tree shaking still works
const unused = x => x
unused(123)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
description: 'verify property accesses are retained for getters with side effects',
options: { treeshake: { propertyReadSideEffects: 'always' } }
};
14 changes: 14 additions & 0 deletions test/function/samples/propertyReadSideEffects-always/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
let effects = 0
var obj = {}
Object.defineProperty(obj, 'x', {
get() {
++effects
}
})
let value
({x: value} = obj)
obj.x
obj["x"]
const {x} = obj

assert.strictEqual(effects, 4)