Skip to content

Commit

Permalink
fix: handle $store imported in module script (#404)
Browse files Browse the repository at this point in the history
* (fix) handle $store imported in module script

Fixes #401

* lint

Co-authored-by: Simon Holthausen <simon.holthausen@accso.de>
  • Loading branch information
dummdidumm and Simon Holthausen committed Sep 9, 2021
1 parent fe3179f commit 162faa4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/transformers/typescript.ts
Expand Up @@ -135,15 +135,24 @@ function injectVarsToCode({
: v.name,
);

const contentForCodestores =
content +
// Append instance script content because it's valid
// to import a store in module script and autosubscribe to it in instance script
(attributes?.context === 'module' ? getScriptContent(markup, false) : '');

// This regex extracts all possible store variables
// TODO investigate if it's possible to achieve this with a
// TS transformer (previous attemps have failed)
const codestores = Array.from(
content.match(/\$[^\s();:,[\]{}.?!+-=*/~|&%<>^`"']+/g) || [],
contentForCodestores.match(/\$[^\s();:,[\]{}.?!+-=*/~|&%<>^`"']+/g) || [],
(name) => name.slice(1),
).filter((name) => !JAVASCRIPT_RESERVED_KEYWORD_SET.has(name));

const varsString = [...codestores, ...varnames].join(',');
const injectedVars = `const $$vars$$ = [${varsString}];`;
// Append instance/markup script content because it's valid
// to import things in one and reference it in the other.
const injectedCode =
attributes?.context === 'module'
? `${sep}${getScriptContent(markup, false)}\n${injectedVars}`
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/TypeScriptImports.svelte
@@ -1,4 +1,5 @@
<script lang="ts" context="module">
import { storeModuleTemplateOnly, storeModuleScriptOnly } from "./store";
onlyUsedInModuleScript;
</script>

Expand Down Expand Up @@ -37,6 +38,7 @@
e.preventDefault();
}
$storeScriptOnly;
$storeModuleScriptOnly;
</script>

<style>
Expand All @@ -51,6 +53,7 @@
</svelte:head>

{$storeTemplateOnly}
{$storeModuleTemplateOnly}

<div>
<Nested let:var1 let:var2={var3}>
Expand Down
3 changes: 3 additions & 0 deletions test/transformers/typescript.test.ts
Expand Up @@ -132,6 +132,9 @@ describe('transformer - typescript', () => {
expect(code).toContain(
`import { onlyUsedInModuleScript } from "./modulescript";`,
);
expect(code).toContain(
`import { storeModuleTemplateOnly, storeModuleScriptOnly } from "./store";`,
);
// Test that comments are properly preserved
expect(code).toContain('<!-- Some comment -->');
});
Expand Down

0 comments on commit 162faa4

Please sign in to comment.