Skip to main content

常见问题

我是 Svelte 的新手。我应该从哪里开始?(I’m new to Svelte. Where should I start?)

¥I’m new to Svelte. Where should I start?

我们认为开始的最佳方式是通过交互式 tutorial 进行操作。那里的每个步骤主要集中于一个特定方面,并且易于遵循。你将直接在浏览器中编辑和运行真正的 Svelte 组件。

¥We think the best way to get started is playing through the interactive tutorial. Each step there is mainly focused on one specific aspect and is easy to follow. You’ll be editing and running real Svelte components right in your browser.

五到十分钟就足以让你启动并运行。一个半小时应该可以让你完成整个教程。

¥Five to ten minutes should be enough to get you up and running. An hour and a half should get you through the entire tutorial.

我在哪里可以获得支持?(Where can I get support?)

¥Where can I get support?

如果你的问题是关于某些语法,参考文档 是一个很好的起点。

¥If your question is about certain syntax, the reference docs are a good place to start.

Stack Overflow 是一个流行的论坛,用于询问代码级问题或解决特定错误。阅读标有 Svelte询问你自己的 的现有问题!

¥Stack Overflow is a popular forum to ask code-level questions or if you’re stuck with a specific error. Read through the existing questions tagged with Svelte or ask your own!

有在线论坛和聊天室,是讨论最佳实践、应用架构或只是结识其他 Svelte 用户的好地方。我们的 DiscordReddit 通道 就是示例。如果你有一个可回答的代码级问题,Stack Overflow 通常更适合。

¥There are online forums and chats which are a great place for discussion about best practices, application architecture or just to get to know fellow Svelte users. Our Discord or the Reddit channel are examples of that. If you have an answerable code-level question, Stack Overflow is usually a better fit.

是否有任何第三方资源?(Are there any third-party resources?)

¥Are there any third-party resources?

Svelte Society 维护 书籍和视频列表

¥Svelte Society maintains a list of books and videos.

如何让 VS Code 语法高亮显示我的 .svelte 文件?(How can I get VS Code to syntax-highlight my .svelte files?)

¥How can I get VS Code to syntax-highlight my .svelte files?

有一个 Svelte 的官方 VS Code 扩展

¥There is an official VS Code extension for Svelte.

有没有工具可以自动格式化我的 .svelte 文件?(Is there a tool to automatically format my .svelte files?)

¥Is there a tool to automatically format my .svelte files?

你可以将 Prettier 与 prettier-plugin-svelte 插件一起使用。

¥You can use prettier with the prettier-plugin-svelte plugin.

如何记录我的组件?(How do I document my components?)

¥How do I document my components?

在使用 Svelte 语言服务器的编辑器中,你可以使用特殊格式的注释记录组件、函数和导出。

¥In editors which use the Svelte Language Server you can document Components, functions and exports using specially formatted comments.

`

<script>
	/** What should we call the user? */
	export let name = 'world';
</script>

<!--
@component
Here's some documentation for this component.
It will show up on hover.

- You can use markdown here.
- You can also use code blocks here.
- Usage:

tsx

``` -->

Hello, {name}

````

注意:在描述组件的 HTML 注释中,@component 是必需的。

¥Note: The @component is necessary in the HTML comment which describes your component.

Svelte 可以扩展吗?(Does Svelte scale?)

¥Does Svelte scale?

最终会有一篇关于此内容的博客文章,但与此同时,请查看 此问题

¥There will be a blog post about this eventually, but in the meantime, check out this issue.

有 UI 组件库吗?(Is there a UI component library?)

¥Is there a UI component library?

有多个 UI 组件库以及独立组件。在 Svelte Society 网站上的 组件页面的设计系统部分 下找到它们。

¥There are several UI component libraries as well as standalone components. Find them under the design systems section of the components page on the Svelte Society website.

如何测试 Svelte 应用?(How do I test Svelte apps?)

¥How do I test Svelte apps?

你的应用的结构以及逻辑的定义位置将决定确保对其进行正确测试的最佳方法。需要注意的是,并非所有逻辑都属于组件 - 这包括数据转换、跨组件状态管理和日志记录等问题。请记住,Svelte 库有自己的测试套件,因此你无需编写测试来验证 Svelte 提供的实现细节。

¥How your application is structured and where logic is defined will determine the best way to ensure it is properly tested. It is important to note that not all logic belongs within a component - this includes concerns such as data transformation, cross-component state management, and logging, among others. Remember that the Svelte library has its own test suite, so you do not need to write tests to validate implementation details provided by Svelte.

Svelte 应用通常有三种不同类型的测试:单元、组件和端到端 (E2E)。

¥A Svelte application will typically have three different types of tests: Unit, Component, and End-to-End (E2E).

单元测试:专注于单独测试业务逻辑。通常这是在验证单个函数和边缘情况。通过最小化这些测试的表面积,它们可以保持精简和快速,并且通过从 Svelte 组件中提取尽可能多的逻辑,可以使用它们覆盖更多应用。创建新的 SvelteKit 项目时,系统会询问你是否要设置 Vitest 进行单元测试。还有许多其他测试运行器也可以使用。

¥Unit Tests: Focus on testing business logic in isolation. Often this is validating individual functions and edge cases. By minimizing the surface area of these tests they can be kept lean and fast, and by extracting as much logic as possible from your Svelte components more of your application can be covered using them. When creating a new SvelteKit project, you will be asked whether you would like to setup Vitest for unit testing. There are a number of other test runners that could be used as well.

组件测试:验证 Svelte 组件在其整个生命周期中是否按预期挂载和交互需要一个提供文档对象模型 (DOM) 的工具。组件可以编译(因为 Svelte 是一个编译器,而不是一个普通的库)并安装,以允许针对元素结构、监听器、状态以及 Svelte 组件提供的所有其他功能进行断言。组件测试工具范围从与 Vitest 等测试运行器配对的内存实现(如 jsdom)到利用实际浏览器提供可视化测试功能(如 PlaywrightCypress)的解决方案。

¥Component Tests: Validating that a Svelte component mounts and interacts as expected throughout its lifecycle requires a tool that provides a Document Object Model (DOM). Components can be compiled (since Svelte is a compiler and not a normal library) and mounted to allow asserting against element structure, listeners, state, and all the other capabilities provided by a Svelte component. Tools for component testing range from an in-memory implementation like jsdom paired with a test runner like Vitest to solutions that leverage an actual browser to provide a visual testing capability such as Playwright or Cypress.

端到端测试:为了确保你的用户能够与你的应用交互,有必要以尽可能接近生产的方式对其进行整体测试。这是通过编写端到端 (E2E) 测试来完成的,该测试加载并与应用的已部署版本交互,以模拟用户如何与应用交互。创建新的 SvelteKit 项目时,系统会询问你是否要设置 Playwright 进行端到端测试。还有许多其他 E2E 测试库可供使用。

¥End-to-End Tests: To ensure your users are able to interact with your application it is necessary to test it as a whole in a manner as close to production as possible. This is done by writing end-to-end (E2E) tests which load and interact with a deployed version of your application in order to simulate how the user will interact with your application. When creating a new SvelteKit project, you will be asked whether you would like to setup Playwright for end-to-end testing. There are many other E2E test libraries available for use as well.

一些开始测试的资源:

¥Some resources for getting started with testing:

有路由吗?(Is there a router?)

¥Is there a router?

官方路由库是 SvelteKit。SvelteKit 在一个易于使用的包中提供了文件系统路由、服务器端渲染 (SSR) 和热模块重新加载 (HMR)。它与 Next.js for React 有相似之处。

¥The official routing library is SvelteKit. SvelteKit provides a filesystem router, server-side rendering (SSR), and hot module reloading (HMR) in one easy-to-use package. It shares similarities with Next.js for React.

但是,你可以使用任何路由库。很多人使用 page.js。还有 navaid,它非常相似。universal-router 与子路由同构,但没有内置历史记录支持。

¥However, you can use any router library. A lot of people use page.js. There’s also navaid, which is very similar. And universal-router, which is isomorphic with child routes, but without built-in history support.

如果你更喜欢声明式 HTML 方法,那么有同构 svelte-routing 库和一个名为 svelte-navigator 的分支,其中包含一些附加功能。

¥If you prefer a declarative HTML approach, there’s the isomorphic svelte-routing library and a fork of it called svelte-navigator containing some additional functionality.

如果你需要在客户端进行基于哈希的路由,请查看 svelte-spa-routerabstract-state-router

¥If you need hash-based routing on the client side, check out svelte-spa-router or abstract-state-router.

Routify 是另一个基于文件系统的路由,类似于 SvelteKit 的路由。版本 3 支持 Svelte 的原生 SSR。

¥Routify is another filesystem-based router, similar to SvelteKit’s router. Version 3 supports Svelte’s native SSR.

你可以看到 sveltesociety.dev 上社区维护的路由列表

¥You can see a community-maintained list of routers on sveltesociety.dev.

如何使用 Svelte 编写移动应用?(How do I write a mobile app with Svelte?)

¥How do I write a mobile app with Svelte?

虽然大多数移动应用都是在不使用 JavaScript 的情况下编写的,但如果你想在构建移动应用时利用现有的 Svelte 组件和对 Svelte 的了解,你可以使用 TauriCapacitorSvelteKit SPA 转变为移动应用。相机、地理位置和推送通知等移动功能可通过两个平台的插件使用。

¥While most mobile apps are written without using JavaScript, if you’d like to leverage your existing Svelte components and knowledge of Svelte when building mobile apps, you can turn a SvelteKit SPA into a mobile app with Tauri or Capacitor. Mobile features like the camera, geolocation, and push notifications are available via plugins for both platforms.

Svelte Native 是 Svelte 4 的一个可用选项,但请注意,Svelte 5 目前不支持它。Svelte Native 允许你使用包含 NativeScript UI 组件 而不是 DOM 元素的 Svelte 组件编写 NativeScript 应用,这对于来自 React Native 的用户来说可能很熟悉。

¥Svelte Native was an option available for Svelte 4, but note that Svelte 5 does not currently support it. Svelte Native lets you write NativeScript apps using Svelte components that contain NativeScript UI components rather than DOM elements, which may be familiar for users coming from React Native.

我可以告诉 Svelte 不要删除我未使用的样式吗?(Can I tell Svelte not to remove my unused styles?)

¥Can I tell Svelte not to remove my unused styles?

否。Svelte 会从组件中删除样式并向你发出警告,以防止出现问题。

¥No. Svelte removes the styles from the component and warns you about them in order to prevent issues that would otherwise arise.

Svelte 的组件样式范围通过生成给定组件独有的类、将其添加到 Svelte 控制下的组件中的相关元素,然后将其添加到该组件样式中的每个选择器来工作。当编译器无法看到样式选择器适用于哪些元素时,有两个不好的选择来保留它:

¥Svelte’s component style scoping works by generating a class unique to the given component, adding it to the relevant elements in the component that are under Svelte’s control, and then adding it to each of the selectors in that component’s styles. When the compiler can’t see what elements a style selector applies to, there would be two bad options for keeping it:

  • 如果它保留选择器并将范围类添加到其中,则选择器很可能与组件中的预期元素不匹配,如果它们是由子组件或 {@html ...} 创建的,则它们肯定不会匹配。

    ¥If it keeps the selector and adds the scoping class to it, the selector will likely not match the expected elements in the component, and they definitely won’t if they were created by a child component or {@html ...}.

  • 如果它保留选择器而不向其添加范围类,则给定的样式将成为全局样式,影响整个页面。

    ¥If it keeps the selector without adding the scoping class to it, the given style will become a global style, affecting your entire page.

如果你需要在编译时设置 Svelte 无法识别的内容的样式,则需要使用 :global(...) 明确选择全局样式。但也请记住,你只能将 :global(...) 封装在选择器的一部分周围。.foo :global(.bar) { ... } 将为组件的 .foo 元素中出现的任何 .bar 元素设置样式。只要当前组件中有一些父元素可以从中开始,像这样的部分全局选择器几乎总是能够让你得到你想要的。

¥If you need to style something that Svelte can’t identify at compile time, you will need to explicitly opt into global styles by using :global(...). But also keep in mind that you can wrap :global(...) around only part of a selector. .foo :global(.bar) { ... } will style any .bar elements that appear within the component’s .foo elements. As long as there’s some parent element in the current component to start from, partially global selectors like this will almost always be able to get you what you want.

Svelte v2 还可用吗?(Is Svelte v2 still available?)

¥Is Svelte v2 still available?

不会添加新功能,并且可能只会在错误非常严重或存在某种安全漏洞时才会修复。

¥New features aren’t being added to it, and bugs will probably only be fixed if they are extremely nasty or present some sort of security vulnerability.

文档仍然可用 此处

¥The documentation is still available here.

如何进行热模块重新加载?(How do I do hot module reloading?)

¥How do I do hot module reloading?

我们建议使用 SvelteKit,它开箱即用地支持 HMR,并且建立在 Vitesvelte-hmr 之上。还有针对 rollupwebpack 的社区插件。

¥We recommend using SvelteKit, which supports HMR out of the box and is built on top of Vite and svelte-hmr. There are also community plugins for rollup and webpack.

上一页 下一页