跳至主要內容

Svelte 4 遷移指南

本遷移指南概述如何從 Svelte 版本 3 遷移到 4。請參閱連結的 PR,以瞭解每個變更的詳細資訊。使用遷移腳本自動遷移其中一些:npx svelte-migrate@latest svelte-4

如果您是函式庫的作者,請考慮是否僅支援 Svelte 4,或者是否可以同時支援 Svelte 3。由於大多數重大變更不會影響許多人,因此這可能很容易實現。此外,請記得更新您 peerDependencies 中的版本範圍。

最低版本要求

  • 升級至 Node 16 或更高版本。不再支援早期版本。( #8566 )
  • 如果您正在使用 SvelteKit,請升級至 1.20.4 或更新版本 ( sveltejs/kit#10172 )
  • 如果您正在使用沒有 SvelteKit 的 Vite,請升級至 vite-plugin-svelte 2.4.1 或更新版本 ( #8516 )
  • 如果您正在使用 webpack,請升級至 webpack 5 或更高版本,以及 svelte-loader 3.1.8 或更高版本。不再支援早期版本。( #8515, 198dbcf )
  • 如果您正在使用 Rollup,請升級至 rollup-plugin-svelte 7.1.5 或更高版本 ( 198dbcf )
  • 如果您正在使用 TypeScript,請升級至 TypeScript 5 或更高版本。較低版本可能仍然可以使用,但不保證。( #8488 )

打包工具的瀏覽器條件

現在,當為瀏覽器建置前端套件時,打包工具必須指定 browser 條件。SvelteKit 和 Vite 會為您自動處理此問題。如果您正在使用其他任何工具,您可能會觀察到生命週期回呼(例如 onMount )未被呼叫,並且您需要更新模組解析配置。

  • 對於 Rollup,這是透過在 @rollup/plugin-node-resolve 外掛程式的選項中設定 browser: true 來完成的。請參閱 rollup-plugin-svelte 文件以瞭解更多詳細資訊
  • 對於 webpack,這是透過將 "browser" 新增至 conditionNames 陣列來完成的。如果已設定,您也可能必須更新 alias 設定。請參閱 svelte-loader 文件以瞭解更多詳細資訊

(#8516)

Svelte 不再支援編譯器輸出的 CommonJS (CJS) 格式,並且也移除了 svelte/register 鉤子和 CJS 執行階段版本。如果您需要保留 CJS 輸出格式,請考慮使用打包工具在建置後步驟中將 Svelte 的 ESM 輸出轉換為 CJS。( #8613 )

Svelte 函數的更嚴格類型

現在,createEventDispatcherActionActionReturnonMount 具有更嚴格的類型

  • createEventDispatcher 現在支援指定 payload 是可選、必要還是不存在,並會相應檢查呼叫站點 ( #7224 )
import { function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>

Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.

Component events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.

The event dispatcher can be typed to narrow the allowed event names and the type of the detail argument:

const dispatch = createEventDispatcher&#x3C;{
 loaded: never; // does not take a detail argument
 change: string; // takes a detail argument of type string, which is required
 optional: number | null; // takes an optional detail argument of type number
}>();
@deprecatedUse callback props and/or the $host() rune instead — see https://svelte.dev.org.tw/docs/svelte/v5-migration-guide#Event-changes-Component-events
createEventDispatcher
} from 'svelte';
const
const dispatch: EventDispatcher<{
    optional: number | null;
    required: string;
    noArgument: null;
}>
dispatch
=
createEventDispatcher<{
    optional: number | null;
    required: string;
    noArgument: null;
}>(): EventDispatcher<{
    optional: number | null;
    required: string;
    noArgument: null;
}>

Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.

Component events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.

The event dispatcher can be typed to narrow the allowed event names and the type of the detail argument:

const dispatch = createEventDispatcher&#x3C;{
 loaded: never; // does not take a detail argument
 change: string; // takes a detail argument of type string, which is required
 optional: number | null; // takes an optional detail argument of type number
}>();
@deprecatedUse callback props and/or the $host() rune instead — see https://svelte.dev.org.tw/docs/svelte/v5-migration-guide#Event-changes-Component-events
createEventDispatcher
<{
optional: number | nulloptional: number | null; required: stringrequired: string; noArgument: nullnoArgument: null; }>(); // Svelte version 3:
const dispatch: EventDispatcher
<"optional">(type: "optional", parameter?: number | null | undefined, options?: DispatchOptions | undefined) => boolean
dispatch
('optional');
const dispatch: EventDispatcher
<"required">(type: "required", parameter: string, options?: DispatchOptions | undefined) => boolean
dispatch
('required'); // I can still omit the detail argument
const dispatch: EventDispatcher
<"noArgument">(type: "noArgument", parameter?: null | undefined, options?: DispatchOptions | undefined) => boolean
dispatch
('noArgument', 'surprise'); // I can still add a detail argument
// Svelte version 4 using TypeScript strict mode:
const dispatch: EventDispatcher
<"optional">(type: "optional", parameter?: number | null | undefined, options?: DispatchOptions | undefined) => boolean
dispatch
('optional');
const dispatch: EventDispatcher
<"required">(type: "required", parameter: string, options?: DispatchOptions | undefined) => boolean
dispatch
('required'); // error, missing argument
const dispatch: EventDispatcher
<"noArgument">(type: "noArgument", parameter?: null | undefined, options?: DispatchOptions | undefined) => boolean
dispatch
('noArgument', 'surprise'); // error, cannot pass an argument
  • ActionActionReturn 現在的預設參數類型為 undefined,這表示如果您想要指定此動作接收參數,則需要鍵入泛型。遷移腳本會自動遷移此問題 ( #7442 )
const action: Action = (node, params) => { ... } // this is now an error if you use params in any way
const const action: Action<HTMLElement, string>action: type Action = /*unresolved*/ anyAction<HTMLElement, string> = (node: anynode, params: anyparams) => { ... } // params is of type string
  • 如果從 onMount 異步返回函數,onMount 現在會顯示類型錯誤,因為這可能是您程式碼中的錯誤,您期望回呼在銷毀時被呼叫,但它只會針對同步返回的函數執行此操作 ( #8136 )
// Example where this change reveals an actual bug
onMount(
	// someCleanup() not called because function handed to onMount is async
	async () => {
		const something = await foo();
           	// someCleanup() is called because function handed to onMount is sync
	() => {
		foo().then(something: anysomething => {...});
		// ...
		return () => someCleanup();
	}
);

使用 Svelte 的自訂元素

使用 Svelte 建立自訂元素已進行全面檢修並顯著改進。tag 選項已棄用,改用新的 customElement 選項

<svelte:options tag="my-component" />
<svelte:options customElement="my-component" />

進行此變更以允許 針對進階使用案例進行更多可配置性。遷移腳本會自動調整您的程式碼。屬性的更新時序也稍微更改。( #8457 )

SvelteComponentTyped 已棄用

SvelteComponentTyped 已棄用,因為 SvelteComponent 現在具有其所有類型功能。將所有 SvelteComponentTyped 執行個體取代為 SvelteComponent

import { SvelteComponentTyped } from 'svelte';
import { class SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>

This was the base class for Svelte components in Svelte 4. Svelte 5+ components are completely different under the hood. For typing, use Component instead. To instantiate components, use mount instead`. See migration guide for more info.

SvelteComponent
} from 'svelte';
export class Foo extends SvelteComponentTyped<{ aProp: string }> {} export class class FooFoo extends class SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>

This was the base class for Svelte components in Svelte 4. Svelte 5+ components are completely different under the hood. For typing, use Component instead. To instantiate components, use mount instead`. See migration guide for more info.

SvelteComponent
<{ aProp: stringaProp: string }> {}

如果您先前使用 SvelteComponent 作為元件執行個體類型,您現在可能會看到有點不透明的類型錯誤,這可以透過將 : typeof SvelteComponent 變更為 : typeof SvelteComponent<any> 來解決。

<script>
	import ComponentA from './ComponentA.svelte';
	import ComponentB from './ComponentB.svelte';
	import { SvelteComponent } from 'svelte';

	let component: typeof SvelteComponent<any>;

	function choseRandomly() {
		component = Math.random() > 0.5 ? ComponentA : ComponentB;
	}
</script>

<button on:click={choseRandomly}>random</button>
<svelte:element this={component} />

遷移腳本會自動為您執行這兩項操作。( #8512 )

轉場效果預設為局部

轉場效果現在預設為局部,以防止頁面導覽時造成混淆。「局部」表示如果轉場效果位於巢狀控制流程區塊 (each/if/await/key) 內,而不是直接父區塊,則不會播放,而是建立/銷毀其上方的區塊。在以下範例中,當 successfalse 變為 true 時,只會播放 slide intro 動畫,但當 showfalse 變為 true 時,則不會播放

{#if show}
	...
	{#if success}
		<p in:slide>Success</p>
	{/each}
{/if}

若要使轉場效果全域,請新增 |global 修飾符 - 則當建立/銷毀上方的任何控制流程區塊時,就會播放。遷移腳本會自動為您執行此操作。( #6686 )

預設插槽綁定

預設插槽綁定不再公開給具名插槽,反之亦然

<script>
	import Nested from './Nested.svelte';
</script>

<Nested let:count>
	<p>
		count in default slot - is available: {count}
	</p>
	<p slot="bar">
		count in bar slot - is not available: {count}
	</p>
</Nested>

這使得插槽綁定更加一致,因為當例如預設插槽來自列表而具名插槽不是時,行為未定義。( #6049 )

預處理器

套用預處理器的順序已變更。現在,預處理器依序執行,並且在一個群組中,順序為 markup、script、style。

import { 
function preprocess(source: string, preprocessor: PreprocessorGroup | PreprocessorGroup[], options?: {
    filename?: string;
} | undefined): Promise<Processed>

The preprocess function provides convenient hooks for arbitrarily transforming component source code. For example, it can be used to convert a &#x3C;style lang="sass"> block into vanilla CSS.

preprocess
} from 'svelte/compiler';
const { const code: string

The new code

code
} = await
function preprocess(source: string, preprocessor: PreprocessorGroup | PreprocessorGroup[], options?: {
    filename?: string;
} | undefined): Promise<Processed>

The preprocess function provides convenient hooks for arbitrarily transforming component source code. For example, it can be used to convert a &#x3C;style lang="sass"> block into vanilla CSS.

preprocess
(
source, [ { PreprocessorGroup.markup?: MarkupPreprocessor | undefinedmarkup: () => { var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('markup-1');
}, PreprocessorGroup.script?: Preprocessor | undefinedscript: () => { var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('script-1');
}, PreprocessorGroup.style?: Preprocessor | undefinedstyle: () => { var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('style-1');
} }, { PreprocessorGroup.markup?: MarkupPreprocessor | undefinedmarkup: () => { var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('markup-2');
}, PreprocessorGroup.script?: Preprocessor | undefinedscript: () => { var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('script-2');
}, PreprocessorGroup.style?: Preprocessor | undefinedstyle: () => { var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
('style-2');
} } ], { filename?: string | undefinedfilename: 'App.svelte' } ); // Svelte 3 logs: // markup-1 // markup-2 // script-1 // script-2 // style-1 // style-2 // Svelte 4 logs: // markup-1 // script-1 // style-1 // markup-2 // script-2 // style-2

如果您正在使用 MDsveX,這可能會影響您 - 在這種情況下,您應該確保它在任何 script 或 style 預處理器之前。

preprocess: [
	vitePreprocess(),
	mdsvex(mdsvexConfig)
	mdsvex(mdsvexConfig),
	vitePreprocess()
]

每個預處理器也必須有一個名稱。( #8618 )

新的 eslint 套件

eslint-plugin-svelte3 已棄用。它可能仍然適用於 Svelte 4,但不保證。建議切換到我們的新套件 eslint-plugin-svelte。請參閱 此 Github 文章,以瞭解如何遷移的說明。或者,您可以使用 npm create svelte@latest 建立一個新專案,選取 eslint (並可能選取 TypeScript) 選項,然後將相關檔案複製到您現有的專案中。

其他重大變更

  • 現在,會將 inert 屬性套用至 outroing 元素,使其對輔助技術不可見並防止互動。( #8628 )
  • 現在,執行階段使用 classList.toggle(name, boolean),這可能在非常舊的瀏覽器中無法使用。如果您需要支援這些瀏覽器,請考慮使用 polyfill。( #8629 )
  • 現在,執行階段使用 CustomEvent 建構函式,這可能在非常舊的瀏覽器中無法使用。如果您需要支援這些瀏覽器,請考慮使用 polyfill。( #8775 )
  • 現在,使用來自 svelte/storeStartStopNotifier 介面(傳遞給 writable 等的 create 函數)從頭開始實作自己的儲存的人員,除了 set 函數之外,還需要傳遞更新函數。這對使用儲存或使用現有的 Svelte 儲存建立儲存的人員沒有影響。( #6750 )
  • derived 現在會針對傳遞給它的虛值而非儲存擲回錯誤。( #7947 )
  • 已移除 svelte/internal 的類型定義,以進一步阻止使用那些非公開 API 的內部方法。其中大部分可能會在 Svelte 5 中變更
  • DOM 節點的移除現在會批次處理,這會稍微改變它們的順序,如果您在這些元素上使用 MutationObserver,可能會影響觸發事件的順序 (#8763)
  • 如果您之前透過 svelte.JSX 命名空間增強了全域類型,您需要將其遷移為使用 svelteHTML 命名空間。同樣地,如果您使用 svelte.JSX 命名空間來使用其中的類型定義,您需要將它們遷移為使用來自 svelte/elements 的類型。您可以在這裡找到更多關於如何操作的資訊

在 GitHub 上編輯此頁面