diff --git a/crates/oxc_minifier/src/options.rs b/crates/oxc_minifier/src/options.rs index c9aeae6d9e508..81cba904cf05c 100644 --- a/crates/oxc_minifier/src/options.rs +++ b/crates/oxc_minifier/src/options.rs @@ -54,6 +54,9 @@ pub struct CompressOptions { /// Limit the maximum number of iterations for debugging purpose. pub max_iterations: Option, + + /// Remove redundant or non-standard directives + pub directives: bool, } impl Default for CompressOptions { @@ -75,6 +78,7 @@ impl CompressOptions { treeshake: TreeShakeOptions::default(), drop_labels: FxHashSet::default(), max_iterations: None, + directives: true, } } @@ -90,6 +94,7 @@ impl CompressOptions { treeshake: TreeShakeOptions::default(), drop_labels: FxHashSet::default(), max_iterations: None, + directives: true, } } @@ -105,6 +110,7 @@ impl CompressOptions { treeshake: TreeShakeOptions::default(), drop_labels: FxHashSet::default(), max_iterations: None, + directives: true, } } } diff --git a/crates/oxc_minifier/src/peephole/normalize.rs b/crates/oxc_minifier/src/peephole/normalize.rs index 66b13f9792211..5c5d76f8db39d 100644 --- a/crates/oxc_minifier/src/peephole/normalize.rs +++ b/crates/oxc_minifier/src/peephole/normalize.rs @@ -52,8 +52,8 @@ impl<'a> Normalize { } impl<'a> Traverse<'a, MinifierState<'a>> for Normalize { - fn exit_program(&mut self, node: &mut Program<'a>, _ctx: &mut TraverseCtx<'a>) { - if node.source_type.is_module() { + fn exit_program(&mut self, node: &mut Program<'a>, ctx: &mut TraverseCtx<'a>) { + if ctx.state.options.directives && node.source_type.is_module() { node.directives.drain_filter(|d| d.directive.as_str() == "use strict"); } } @@ -695,4 +695,30 @@ mod test { test("'use strict'; function _() { 'use strict' }", "function _() {}"); test("'use strict';", ""); } + + #[test] + fn not_remove_unused_use_strict_directive_when_directives_disabled() { + use oxc_span::SourceType; + let mut options = default_options(); + options.directives = false; + let source_type = SourceType::cjs(); + test_options_source_type( + "'use strict'; function _() { 'use strict' }", + "'use strict'; function _() { }", + source_type, + &options, + ); + test_options_source_type( + "function _() { 'use strict'; function __() { 'use strict' } }", + "function _() { 'use strict'; function __() { } }", + source_type, + &options, + ); + test_options( + "'use strict'; function _() { 'use strict' }", + "'use strict'; function _() {}", + &options, + ); + test_options("'use strict';", "'use strict';", &options); + } }