Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { test } from 'vitest';
import { testTransform } from '../../../test';
import stringLiteralInTemplate from '../transforms/string-literal-in-template';

const expectJS = testTransform(stringLiteralInTemplate);

test('string-literal-in-template-literal', () => {
expectJS(
`
const a = \`Hello \${'World'}!\`;
`,
).toMatchInlineSnapshot(`const a = \`Hello World!\`;`);

expectJS(
`
const a = \`Hello \${'World'}\${'!'}\`;
`,
).toMatchInlineSnapshot(`const a = \`Hello World!\`;`);

expectJS(
`
const a = \`\${"Hi!"}\`;
`,
).toMatchInlineSnapshot(`const a = \`Hi!\`;`);
});
1 change: 1 addition & 0 deletions packages/webcrack/src/unminify/transforms/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export { default as removeDoubleNot } from './remove-double-not';
export { default as sequence } from './sequence';
export { default as splitForLoopVars } from './split-for-loop-vars';
export { default as splitVariableDeclarations } from './split-variable-declarations';
export { default as stringLiteralInTemplate } from './string-literal-in-template';
export { default as ternaryToIf } from './ternary-to-if';
export { default as truncateNumberLiteral } from './truncate-number-literal';
export { default as typeofUndefined } from './typeof-undefined';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as t from '@babel/types';
import type { Transform } from '../../ast-utils';

export default {
name: 'string-literal-in-template-literal',
tags: ['safe'],
visitor: () => ({
TemplateLiteral(path) {
// inline string literals in template literals
// e.g. `Hello ${'World'}!` -> `Hello World!`
for (let i = 0; i < path.node.expressions.length; i++) {
const expr = path.node.expressions[i];
if (t.isStringLiteral(expr)) {
path.node.expressions.splice(i, 1);
const main = path.node.quasis[i];
main.value.raw += expr.value;

const next = path.node.quasis[i + 1];
if (next) {
main.value.raw += next.value.raw;
path.node.quasis.splice(i + 1, 1);
}

this.changes++;
i--;
}
}
},
}),
} satisfies Transform;
Loading