diff --git a/packages/svelte/src/preprocessors.ts b/packages/svelte/src/preprocessors.ts index b13b20ec59f6..c7df0e258c0f 100644 --- a/packages/svelte/src/preprocessors.ts +++ b/packages/svelte/src/preprocessors.ts @@ -97,7 +97,7 @@ function shouldInjectFunction( // because the code inside is not executed when the component is instantiated but // when the module is first imported. // see: https://svelte.dev/docs#component-format-script-context-module - if (attributes.context === 'module') { + if (attributes.module || attributes.context === 'module') { return false; } diff --git a/packages/svelte/test/preprocessors.test.ts b/packages/svelte/test/preprocessors.test.ts index 547f58b366ab..207e2d95cce5 100644 --- a/packages/svelte/test/preprocessors.test.ts +++ b/packages/svelte/test/preprocessors.test.ts @@ -170,6 +170,26 @@ describe('componentTrackingPreprocessor', () => { expect(processedComponent.newCode).toEqual(processedComponent.originalCode); }); + + it('doesnt inject the function call to a module context script block with Svelte 5 module attribute', () => { + const preProc = componentTrackingPreprocessor(); + const component = { + originalCode: 'console.log(cmp2)', + filename: 'lib/Cmp2.svelte', + name: 'Cmp2', + }; + + const res: any = preProc.script?.({ + content: component.originalCode, + filename: component.filename, + attributes: { module: true }, + markup: '', + }); + + const processedComponent = { ...component, newCode: res.code, map: res.map }; + + expect(processedComponent.newCode).toEqual(processedComponent.originalCode); + }); }); describe('markup hook', () => {