Skip to content

Commit c6bca7a

Browse files
authored
fix(side-effects): respect DefinePlugin purity evaluation (#13628)
1 parent c8abe3c commit c6bca7a

File tree

7 files changed

+56
-6
lines changed

7 files changed

+56
-6
lines changed

crates/rspack_plugin_javascript/src/parser_plugin/side_effects_parser_plugin.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1661,12 +1661,19 @@ pub fn is_pure_expression<'a>(
16611661
}
16621662
true
16631663
}
1664-
_ => !expr.may_have_side_effects(ExprCtx {
1665-
unresolved_ctxt,
1666-
is_unresolved_ref_safe: true,
1667-
in_strict: false,
1668-
remaining_depth: 4,
1669-
}),
1664+
_ => {
1665+
if !expr.may_have_side_effects(ExprCtx {
1666+
unresolved_ctxt,
1667+
is_unresolved_ref_safe: true,
1668+
in_strict: false,
1669+
remaining_depth: 4,
1670+
}) {
1671+
return true;
1672+
}
1673+
// could_have_side_effects is true by default, so here we test if it's modified by other plugins to return false.
1674+
let evaluated = parser.evaluate_expression(expr);
1675+
!evaluated.could_have_side_effects()
1676+
}
16701677
}
16711678
}
16721679
_is_pure_expression(
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { f } from "./reexport";
2+
3+
it("should not include reexport modules", async () => {
4+
const content = await __non_webpack_require__("fs/promises").readFile(__filename, "utf-8");
5+
expect(f()).toBe(42);
6+
const sideEffectsFreeModules = ["./lib/index" + ".js", "./reexport" + ".js"];
7+
for (const module of sideEffectsFreeModules) {
8+
expect(content).not.toContain(module);
9+
}
10+
});
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export * from "./module";
2+
3+
const createApp = () => {
4+
console.log("__CREATE_APP__");
5+
}
6+
7+
export { createApp };
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function f() {
2+
return 42;
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"sideEffects": false
3+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export * from "./lib/index";
2+
3+
if (!!(process.env.NODE_ENV !== "production")) {
4+
console.log("This is a side effect");
5+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const { rspack } = require('@rspack/core');
2+
3+
/** @type {import("@rspack/core").Configuration} */
4+
module.exports = {
5+
optimization: {
6+
sideEffects: true,
7+
moduleIds: 'named',
8+
concatenateModules: false,
9+
},
10+
plugins: [
11+
new rspack.DefinePlugin({
12+
'process.env.NODE_ENV': JSON.stringify('production'),
13+
}),
14+
],
15+
};

0 commit comments

Comments
 (0)