diff --git a/.changeset/hip-beers-shake.md b/.changeset/hip-beers-shake.md new file mode 100644 index 000000000000..5a124b8d2050 --- /dev/null +++ b/.changeset/hip-beers-shake.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: hoist imports on top diff --git a/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js b/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js index 967bd849ccb1..8405fb4b4019 100644 --- a/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js +++ b/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js @@ -457,7 +457,10 @@ export function client_component(analysis, options) { analysis.uses_slots || analysis.slot_names.size > 0; - const body = [...module.body, ...state.hoisted]; + // we hoist all the import declarations to the top of the file + const body = [...module.body, ...state.hoisted].sort((body_a, body_b) => + body_a.type === 'ImportDeclaration' && body_b.type !== 'ImportDeclaration' ? -1 : 1 + ); const component = b.function_declaration( b.id(analysis.name), diff --git a/packages/svelte/tests/snapshot/samples/inline-module-vars/_expected/client/index.svelte.js b/packages/svelte/tests/snapshot/samples/inline-module-vars/_expected/client/index.svelte.js index 8776c5c09573..d5fa54d80255 100644 --- a/packages/svelte/tests/snapshot/samples/inline-module-vars/_expected/client/index.svelte.js +++ b/packages/svelte/tests/snapshot/samples/inline-module-vars/_expected/client/index.svelte.js @@ -1,4 +1,5 @@ import "svelte/internal/disclose-version"; +import * as $ from "svelte/internal/client"; const __ENHANCED_IMG_1__ = "__VITE_ASSET__2AM7_y_a__"; const __ENHANCED_IMG_2__ = "__VITE_ASSET__2AM7_y_b__"; @@ -6,9 +7,6 @@ const __ENHANCED_IMG_3__ = "__VITE_ASSET__2AM7_y_c__"; const __ENHANCED_IMG_4__ = "__VITE_ASSET__2AM7_y_d__"; const __ENHANCED_IMG_5__ = "__VITE_ASSET__2AM7_y_e__"; const __ENHANCED_IMG_6__ = "__VITE_ASSET__2AM7_y_f__"; - -import * as $ from "svelte/internal/client"; - var root = $.template(` production test`); export default function Inline_module_vars($$anchor) {