Skip to content

Commit 162faa4

Browse files
dummdidummSimon Holthausen
and
Simon Holthausen
authored
fix: handle $store imported in module script (#404)
* (fix) handle $store imported in module script Fixes #401 * lint Co-authored-by: Simon Holthausen <[email protected]>
1 parent fe3179f commit 162faa4

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Diff for: src/transformers/typescript.ts

+10-1
Original file line numberDiff line numberDiff line change
@@ -135,15 +135,24 @@ function injectVarsToCode({
135135
: v.name,
136136
);
137137

138+
const contentForCodestores =
139+
content +
140+
// Append instance script content because it's valid
141+
// to import a store in module script and autosubscribe to it in instance script
142+
(attributes?.context === 'module' ? getScriptContent(markup, false) : '');
143+
144+
// This regex extracts all possible store variables
138145
// TODO investigate if it's possible to achieve this with a
139146
// TS transformer (previous attemps have failed)
140147
const codestores = Array.from(
141-
content.match(/\$[^\s();:,[\]{}.?!+-=*/~|&%<>^`"']+/g) || [],
148+
contentForCodestores.match(/\$[^\s();:,[\]{}.?!+-=*/~|&%<>^`"']+/g) || [],
142149
(name) => name.slice(1),
143150
).filter((name) => !JAVASCRIPT_RESERVED_KEYWORD_SET.has(name));
144151

145152
const varsString = [...codestores, ...varnames].join(',');
146153
const injectedVars = `const $$vars$$ = [${varsString}];`;
154+
// Append instance/markup script content because it's valid
155+
// to import things in one and reference it in the other.
147156
const injectedCode =
148157
attributes?.context === 'module'
149158
? `${sep}${getScriptContent(markup, false)}\n${injectedVars}`

Diff for: test/fixtures/TypeScriptImports.svelte

+3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<script lang="ts" context="module">
2+
import { storeModuleTemplateOnly, storeModuleScriptOnly } from "./store";
23
onlyUsedInModuleScript;
34
</script>
45

@@ -37,6 +38,7 @@
3738
e.preventDefault();
3839
}
3940
$storeScriptOnly;
41+
$storeModuleScriptOnly;
4042
</script>
4143

4244
<style>
@@ -51,6 +53,7 @@
5153
</svelte:head>
5254

5355
{$storeTemplateOnly}
56+
{$storeModuleTemplateOnly}
5457

5558
<div>
5659
<Nested let:var1 let:var2={var3}>

Diff for: test/transformers/typescript.test.ts

+3
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,9 @@ describe('transformer - typescript', () => {
132132
expect(code).toContain(
133133
`import { onlyUsedInModuleScript } from "./modulescript";`,
134134
);
135+
expect(code).toContain(
136+
`import { storeModuleTemplateOnly, storeModuleScriptOnly } from "./store";`,
137+
);
135138
// Test that comments are properly preserved
136139
expect(code).toContain('<!-- Some comment -->');
137140
});

0 commit comments

Comments
 (0)