Expand description
Side effect analysis for JavaScript/TypeScript programs.
This module provides functionality to determine if a javascript script/module has side effects during module evaluation. This is useful for tree-shaking and dead code elimination.
§What are side effects?
A side effect is any observable behavior that occurs when code is executed:
- Function calls (unless marked with
/*#__PURE__*/or otherwise known to be pure) - Constructor calls (unless marked with
/*#__PURE__*/or otherwise known to be pure ) - Assignments to variables or properties
- Property mutations
- Update expressions (
++,--) - Delete expressions
§Conservative Analysis
This analyzer is intentionally conservative. When in doubt, it assumes code has side effects. This is safe for tree-shaking purposes as it prevents incorrectly removing code that might be needed, and can simply be improved over time.
§Future Enhancement: Local Variable Mutation Tracking
Currently, all assignments, updates, and property mutations are treated as side effects. However, mutations to locally-scoped variables that never escape the module evaluation scope could be considered side-effect free. This would handle common patterns like:
// Currently marked as having side effects, but could be pure:
const config = {};
config['a'] = 'a';
config['b'] = 'b';
export default config;A special case to consider would be CJS exports module.exports ={} and export.foo = could
be considered non-effecful just like ESM exports. If we do that we should also consider
changing how require is handled, currently it is considered to be effectful
Functions§
- compute_
module_ evaluation_ side_ effects - Analyzes a program to determine if it contains side effects at the top level.