Skip to content

Commit

Permalink
fix(es/minifier): Use cooked while converting tpls into strings (#8248
Browse files Browse the repository at this point in the history
)

**Related issue:**

 - Closes #8228
  • Loading branch information
kdy1 authored Nov 9, 2023
1 parent 60455b0 commit be748f0
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 2 deletions.
25 changes: 25 additions & 0 deletions crates/swc/tests/fixture/issues-8xxx/8228/input/.swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true
},
"target": "es2017",
"loose": false,
"transform": {
"react": {
"runtime": "automatic"
}
},
"externalHelpers": true,
"keepClassNames": false,
"minify": {
"compress": true
}
},
"module": {
"type": "es6"
},
"minify": false
}
2 changes: 2 additions & 0 deletions crates/swc/tests/fixture/issues-8xxx/8228/input/1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const a = `You\'ll`
export const b = 'You\'ll'
2 changes: 2 additions & 0 deletions crates/swc/tests/fixture/issues-8xxx/8228/output/1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const a = "You'll";
export const b = 'You\'ll';
19 changes: 19 additions & 0 deletions crates/swc_ecma_minifier/src/compress/pure/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,23 @@ impl Pure<'_> {
pub(super) fn convert_tpl_to_str(&mut self, e: &mut Expr) {
match e {
Expr::Tpl(t) if t.quasis.len() == 1 && t.exprs.is_empty() => {
if let Some(value) = &t.quasis[0].cooked {
if value.chars().all(|c| match c {
'\u{0020}'..='\u{007e}' => true,
'\n' | '\r' => self.config.force_str_for_tpl,
_ => false,
}) {
report_change!("converting a template literal to a string literal");

*e = Expr::Lit(Lit::Str(Str {
span: t.span,
raw: None,
value: value.clone(),
}));
return;
}
}

let c = &t.quasis[0].raw;

if c.chars().all(|c| match c {
Expand All @@ -209,6 +226,8 @@ impl Pure<'_> {
.replace("\\r", "\r")
.replace("\\\\", "\\");

report_change!("converting a template literal to a string literal");

*e = Expr::Lit(Lit::Str(Str {
span: t.span,
raw: None,
Expand Down
2 changes: 2 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/8228/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const a = `You\'ll`
export const b = 'You\'ll'
2 changes: 2 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/8228/output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const a = "You'll";
export const b = 'You\'ll';
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
var foo = `<\/script>${content}`;
var bar = `\x3c!--`;
var baz = `--\x3e`;
var bar = "<!--";
var baz = "-->";

0 comments on commit be748f0

Please sign in to comment.