Skip to content

Commit

Permalink
fix: correctly detect script language during compilation (#844)
Browse files Browse the repository at this point in the history
* fix: correctly detect script language during compilation

* fix: correctly handle commented script blocks in compile.js

* chore: add changeset

---------

Co-authored-by: Richard Ivanek <[email protected]>
Co-authored-by: dominikg <[email protected]>
  • Loading branch information
3 people authored Jan 27, 2024
1 parent c36c3ae commit e95d863
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/rare-buttons-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

fix(compile): correctly determine script lang in files where a comment precedes the script tag
31 changes: 31 additions & 0 deletions packages/vite-plugin-svelte/__tests__/compile.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,36 @@ describe('createCompileSvelte', () => {
);
expect(output.compiled.js.code).not.toContain('/* @__PURE__ */\n');
});

it('detects script lang', async () => {
const code = `<!-- this file uses typescript -->
<!--
<script lang="foo">
</script>-->
<script lang="ts" generics="T">
const x = 1;
console.log('something',/* @__PURE__ */ new Date());
console.log('something else');
</script>
<div>{x}</div>`;

const compileSvelte = createCompileSvelte(options);
const output = await compileSvelte(
{
cssId: 'svelte-xxxxx',
query: {},
raw: false,
ssr: false,
timestamp: Date.now(),
id: 'id',
filename: '/some/File.svelte',
normalizedFilename: 'some/File.svelte'
},
code,
{}
);

expect(output.lang).toBe('ts');
});
});
});
12 changes: 10 additions & 2 deletions packages/vite-plugin-svelte/src/utils/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { isSvelte5 } from './svelte-version.js';
// which is closer to the other regexes in at least not falling into commented script
// but ideally would be shared exactly with svelte and other tools that use it
const scriptLangRE =
/<!--[^]*?-->|<script (?:[^>]*|(?:[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)\s+)*)lang=["']?([^"' >]+)["']?[^>]*>/;
/<!--[^]*?-->|<script (?:[^>]*|(?:[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)\s+)*)lang=["']?([^"' >]+)["']?[^>]*>/g;

/**
* @param {Function} [makeHot]
Expand Down Expand Up @@ -184,10 +184,18 @@ export const _createCompileSvelte = (makeHot) => {
}
}

let lang = 'js';
for (const match of code.matchAll(scriptLangRE)) {
if (match[1]) {
lang = match[1];
break;
}
}

return {
filename,
normalizedFilename,
lang: code.match(scriptLangRE)?.[1] || 'js',
lang,
// @ts-ignore
compiled,
ssr,
Expand Down

0 comments on commit e95d863

Please sign in to comment.