sideEffects in package.json
When examining JavaScript projects, you might notice the sideEffects configuration in package.json. What does this mean and how should it be used? Here’s a summary.
sideEffects
As the name suggests, side effects refer to functions that perform conditional filtering and return a new array, but also modify the original array itself.
function filterArr(arr) {
return arr.filter((item, index) => {
arr[index] = Math.random();
return item > 3;
});
}
const arr = [4, 5, 1, 2];
console.log('before:' + arr);
console.log(filterArr(arr));
console.log('after:' + arr);
The opposite of side effects are pure functions, where fixed input produces fixed output.
function filterArr(arr) {
return arr.filter((item) => {
return item > 3;
});
}
const arr = [4, 5, 1, 2];
console.log('before:' + arr);
console.log(filterArr(arr));
console.log('after:' + arr);
In real life, we also talk about side effects - for example, when we take medicine to cure an illness, but the medicine has some toxicity and may cause headaches, etc. So we can say that program functions with side effects are not purely functional.
sideEffects is Not an Official NPM Standard Field
Checking the npmjs official documentation, you won’t find the sideEffects setting explained because it’s not an official standard field. It’s a configuration item proposed by webpack to better implement tree shaking (Webpack4+).
Therefore, tree shaking in webpack requires configuration both in webpack itself and in Package.json.
sideEffects notifies webpack that the module can be safely tree-shaken without worrying about its side effects.
sideEffects Values in Package.json
sideEffects can be false to indicate no side effects, or an array to specify files that do have side effects.
{
"name": "your-project",
"sideEffects": ["./src/some-side-effectful-file.js"]
}
Notes:
Supports wildcards.
Default value is
true
, meaning there are side effects.Side effect granularity is at the file level.
Webpack sideEffects Processing Logic
- If sideEffects is configured as false, all code within the module has no side effects. Any code not imported and used will be deleted, and webpack doesn’t need to analyze it
- If sideEffects specifies certain files, webpack will preserve those files during bundling, even if the side-effectful code within them is not used
Note: Production mode will delete code without side effects that isn’t imported, while development mode will retain it but mark it