Skip to content

Commit a2de6f9

Browse files
authored
feat: transform string literal in template expression (#191)
1 parent 5025919 commit a2de6f9

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { test } from 'vitest';
2+
import { testTransform } from '../../../test';
3+
import stringLiteralInTemplate from '../transforms/string-literal-in-template';
4+
5+
const expectJS = testTransform(stringLiteralInTemplate);
6+
7+
test('string-literal-in-template-literal', () => {
8+
expectJS(
9+
`
10+
const a = \`Hello \${'World'}!\`;
11+
`,
12+
).toMatchInlineSnapshot(`const a = \`Hello World!\`;`);
13+
14+
expectJS(
15+
`
16+
const a = \`Hello \${'World'}\${'!'}\`;
17+
`,
18+
).toMatchInlineSnapshot(`const a = \`Hello World!\`;`);
19+
20+
expectJS(
21+
`
22+
const a = \`\${"Hi!"}\`;
23+
`,
24+
).toMatchInlineSnapshot(`const a = \`Hi!\`;`);
25+
});

packages/webcrack/src/unminify/transforms/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export { default as removeDoubleNot } from './remove-double-not';
1313
export { default as sequence } from './sequence';
1414
export { default as splitForLoopVars } from './split-for-loop-vars';
1515
export { default as splitVariableDeclarations } from './split-variable-declarations';
16+
export { default as stringLiteralInTemplate } from './string-literal-in-template';
1617
export { default as ternaryToIf } from './ternary-to-if';
1718
export { default as truncateNumberLiteral } from './truncate-number-literal';
1819
export { default as typeofUndefined } from './typeof-undefined';
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import * as t from '@babel/types';
2+
import type { Transform } from '../../ast-utils';
3+
4+
export default {
5+
name: 'string-literal-in-template-literal',
6+
tags: ['safe'],
7+
visitor: () => ({
8+
TemplateLiteral(path) {
9+
// inline string literals in template literals
10+
// e.g. `Hello ${'World'}!` -> `Hello World!`
11+
for (let i = 0; i < path.node.expressions.length; i++) {
12+
const expr = path.node.expressions[i];
13+
if (t.isStringLiteral(expr)) {
14+
path.node.expressions.splice(i, 1);
15+
const main = path.node.quasis[i];
16+
main.value.raw += expr.value;
17+
18+
const next = path.node.quasis[i + 1];
19+
if (next) {
20+
main.value.raw += next.value.raw;
21+
path.node.quasis.splice(i + 1, 1);
22+
}
23+
24+
this.changes++;
25+
i--;
26+
}
27+
}
28+
},
29+
}),
30+
} satisfies Transform;

0 commit comments

Comments
 (0)