Tree Shake
Farm supports Tree Shake, which is automatically enabled in the default Production environment. It can be turned on or off by the compilation.treeShaking
option.
During Tree Shake, the sideEffects
field in package.json will be automatically read, and modules with sideEffects
will not perform Tree Shake.
Farm will treat all circularly dependent modules as sideEffects and will not perform Tree Shake. Please try to avoid circular dependencies in your project.
Tree shake example:
import { b1, b2 } from 'b';
console.log(b1);
export b1 = "B1";
export b2 = "B2";
a.js
is entry and it imports b.js
, after tree shaking, the result is:
import { b1 } from 'b';
console.log(b1);
export b1 = "B1";
b2
is not used and will be removed in both a.js
and b.js
Configuring Tree Shake​
Tree Shake is enabled in production mode by default, to disable tree shake, use compilation.treeShaking
:
export default {
compilation: {
treeShaking: false,
},
};
Deal With Side Effects​
When a module contains side effects
, Farm won't apply tree shake for it, and all of its imported and exports are treated as used. Farm will think following modules have side effects
:
- CommonJs modules always have side effects.
- A module contains
self-executed
statement at global scope has side effects - Modules that contains cyclic dependencies has side effects
- Modules matches
sideEffects
config in its closestpackage.json
- Entry modules are always has side effects.
Example 1:
const a = require('./')
module.exports = a;
CommonJs module are always has side effects.
Example 2:
import a from './';
a();
a()
is executed at global scope and we treat it as side effect.
Example 3:
// a.js
import b from './b.js'
// b.js
import a from './a.js'
a
, b
are cyclic dependencies, so they will be treated as side effects too.
Example 4:
{
"name": "my-package",
"sideEffects": [
"./global/**.ts"
]
}
all ts modules under global/
are treat as side effects.