Although the initial release of Svelte was back in November 2016, it’s still more of an underdog amongst the JavaScript front-end frameworks and just recently started to get its well-deserved attention in the community.
尽管Svelte的最初版本是在2016年11月,但是它在JavaScript前端框架中仍然处于劣势,并且最近才开始在社区中引起其应有的关注。
After working with various JavaScript frameworks over the years, including Angular, React, and Vue.js, I think I have a good overall idea of how writing code can be both enjoyable and frustrating.
多年来,在使用了各种JavaScript框架(包括Angular,React和Vue.js)之后,我认为我对编写代码的乐趣和挫败感有很好的总体了解。
A couple of years ago, writing code with jQuery felt like a revelation when coming from pure JavaScript. Then at my first job, I started working with Angular 2, and all of a sudden jQuery felt like a drag. Now, React is the cool kid on the block and Angular feels so complicated in comparison. You can probably see where this is going!
几年前,当使用纯JavaScript时,用jQuery编写代码就像是一种启示。 然后,在我的第一份工作中,我开始使用Angular 2,突然之间,jQuery感觉就像是在拖累。 现在,React是一个很酷的孩子,与之相比,Angular感觉是如此复杂。 您可能会看到前进的方向!
For me, Svelte is the next evolutionary step in the rapidly changing ecosystem of JavaScript frameworks. It feels so easy to write the Svelte way and you can tell that its creator, Rich Harris, was tired of all the annoying abstractions and the necessary boilerplate code that the existing frameworks require you to learn.
对我而言,Svelte是快速变化JavaScript框架生态系统中的下一步发展步骤。 编写Svelte方式非常容易,您可以说它的创建者Rich Harris厌倦了现有框架要求您学习的所有烦人的抽象和必要的样板代码。
Now you might be asking yourself this question: “What makes Svelte different?”
现在您可能会问自己一个问题:“什么使Svelte与众不同?”
You might have heard about Svelte appearing here and there in articles like “A RealWorld Comparison of Front-End Frameworks” and developer surveys like the State of JS Survey as one of the highest-ranking frameworks when it comes to bundle size, performance, lines of code, and most importantly, developer satisfaction.
您可能已经听说过Svelte出现在诸如“前端框架的真实世界比较”之类的文章中,以及诸如JS状况调查之类的开发人员调查,这些调查在捆绑大小,性能,生产线方面是排名最高的框架之一。代码,最重要的是,开发人员的满意度。
Compared to the popular React and Vue.js libraries, which do the bulk work during runtime and use a technique called “virtual DOM diffing” for detecting changes, Svelte is compiled into framework-less vanilla JavaScript as a build step and can therefore benefit from a lot of code optimizations.
与流行的React和Vue.js库相比,它们在运行时进行大量工作并使用一种称为“虚拟DOM差异”的技术来检测更改,相比而言,Svelte作为构建步骤被编译为无框架的原始JavaScript,因此可以从中受益很多代码优化。
Naturally hesitant, I dismissed Svelte at first as “just another JavaScript framework” and didn’t bother looking into it. After hearing about it a second time, I wondered, “Is Svelte just hyped or could it really be that good?” I decided to battle-test it and use it on a personal project of mine.
自然地犹豫不决,我一开始就把Svelte视作“只是另一个JavaScript框架”而已,并没有理会它。 在第二次听到这句话之后,我想知道:“Card.svelte只是大肆宣传还是真的那么好?” 我决定对其进行战斗测试,并将其用于我的个人项目中。
Now after a few months, I can give you a definitive answer: Svelte is simple, powerful, and elegant — and you will love it!
现在过了几个月,我可以给您一个明确的答案:Svelte简单,强大,优雅-您一定会喜欢的!
Without further ado, these are the top ten reasons why I recommend Svelte to every new web developer who is starting to learn programming.
事不宜迟,这些就是我向所有开始学习编程的新Web开发人员推荐Svelte的十大理由。
1.精巧的组件易于理解 (1. Svelte Components Are Easy to Understand)
If you have never seen the Svelte syntax before, this is what a simple example would look like:
如果您以前从未看过Svelte语法,那么这是一个简单的示例:
<style>
h1 {
color: green;
}
p {
font-style: italic;
}
</style>
<script>
let role = 'developer';
</script>
<h1>Hello, {role}!</h1>
<p>I hope you are having a good day!</p>
2.只需编写简洁的代码(2. Simply Write Concise Code)
As you can see in the code example above, the business logic that you write is simple and easily readable at the same time. After all, the less code you write, the fewer bugs it can have, right?
正如您在上面的代码示例中看到的那样,您编写的业务逻辑既简单又易于阅读。 毕竟,您编写的代码越少,它可以拥有的错误就越少,对吗?
Rich Harris, the genius creator of Svelte, provided some good comparisons with React and Vue.js in his article called “Write less code.” According to his check up on characters needed to write the logic for the simple addition of two numbers, a React component is typically around 40% larger than its Svelte equivalent!
Svelte的天才创造者Rich Harris在他的文章“更少编写代码”中对React和Vue.js进行了很好的比较。 根据他对编写两个数字的简单加法逻辑所需的字符的检查,React组件通常比其Svelte等效组件大40%左右!
3.与标记语句的React性 (3. Reactivity With Labeled Statements)
Whenever you want your variable values to update and recompute based on other variables, you can use reactive declarations. Just put a dollar sign in front of the variable that you want to be reactive and you’re good to go!
每当您希望变量值基于其他变量进行更新和重新计算时,都可以使用React式声明。 只需在要进行React的变量前面放一个美元符号,就可以了!
Any time the button is clicked, count
will increase by one and doubled
will know that the value of count
changed and update accordingly. It's really fascinating to think in terms of reactivity and it feels good to write.
任何时候单击该按钮, count
都会增加doubled
,并且doubled
会知道count
更改并相应更新。 考虑到React性,这真的很有趣,并且写起来感觉很好。
<script>
let count = 0;
$: doubled = count * 2;
function handleClick() {
count += 1;
}
</script>
<button on:click="{handleClick}">Click me!</button>
<p>{count} doubled is {doubled}</p>
4.简便的全球状态管理(4. Easy Global State Management Out of the Box)
No need for any complicated third-party state management tools like Redux or Vuex.
不需要任何复杂的第三方状态管理工具,例如Redux或Vuex 。
You just define a variable as a writable/readable store and use it in any .svelte
file prefixed with a $
sign.
您只需将变量定义为可写/可读存储,然后在任何带有$
符号前缀的.svelte
文件中使用它。
// stores.js
import { writable } from 'svelte/store';
export const isDev = writable(NODE_ENV === 'development');
In this example, we check the current environment, which exists as a value in our store, and use it to decide if the cookie notice should be displayed or not. Simple, isn’t it?
在此示例中,我们检查当前环境,该环境作为商店中的值存在,并使用它来确定是否应显示cookie通知。 很简单,不是吗?
With Svelte stores, you also never have to worry about memory leaks because store variables prefixed with a $
sign act as auto-subscriptions and unsubscribe automatically.
使用Svelte存储库,您也不必担心内存泄漏,因为以$
符号为前缀的存储变量会自动订阅并自动取消订阅。
5.内置可访问性和未使用CSS检查 (5. Built-In Accessibility and Unused CSS Checks)
Svelte wants to make the internet a better place and helps you out with useful hints in the code.
Svelte希望使互联网变得更美好,并通过代码中的有用提示帮助您。
Whenever you forget to put the alt
attribute on an <img>
tag, Svelte will display an A11y: <img> element should have an alt attribute
reminder for you. There is a long list of accessibility checks that are implemented in Svelte, and they provide hints without ever becoming a nuisance.
每当您忘记将alt
属性放在<img>
标记上时,Svelte都会显示A11y: <img> element should have an alt attribute
为您A11y: <img> element should have an alt attribute
提醒。 在Svelte中实现了很长的可访问性检查列表,它们提供提示而丝毫不会造成麻烦。
To keep the code as concise as possible and to avoid snippets of leftover code, Svelte also flags unused CSS selectors for you whenever there is no respective markup to be found in a component.
为了使代码尽可能简洁,并避免残留代码片段,当在组件中找不到相应的标记时,Svelte还会为您标记未使用CSS选择器。
6.组件自动导出 (6. Components Are Exported Automatically)
Whenever you would want to use component A in component B, you would usually need to write code to export component A first so it can get imported by component B. With Svelte, you don’t ever need to worry about forgetting to export. A .svelte
component is always exported by default for you automatically and ready to be imported by any other component.
每当您想在组件B中使用组件A时,通常都需要先编写代码以导出组件A,这样它才能被组件B导入。使用Svelte,您不必担心忘记导出。 默认情况下,始终自动为您导出.svelte
组件,并准备将其导入其他任何组件。
7.样式默认为范围 (7. Styling Is Scoped by Default)
Similarly to CSS-in-JS libraries, Svelte styles are scoped by default, which means that a svelte-<unique-hash>
class name will be attached to your styles so they don't leak and influence any other component’s styling. Of course, you have the option for styles to be applied globally by simply prefixing them with the :global()
modifier or using a .css
file if you want to.
与CSS-in-JS库类似,默认情况下Svelte样式是作用域的,这意味着svelte-<unique-hash>
类名称将附加到您的样式,这样它们就不会泄漏并影响任何其他组件的样式。 当然,您可以选择在全局范围内应用样式,只需在它们前面加上:global()
修饰符即可,如果需要,也可以使用.css
文件。
8. #await块 (8. #await Blocks)
With most web applications, you will need to handle asynchronous data to display useful stats to your users.
对于大多数Web应用程序,您将需要处理异步数据以向用户显示有用的统计信息。
{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
The advantage of {#await}
blocks is that you don't have to define an extra state for your resolved/rejected promises. You can just define variables inline in your template.
{#await}
块的优点是您不必为已解决/已拒绝的承诺定义额外的状态。 您可以在模板中内联定义变量。
9.传递道具的简写属性 (9. Shorthand Attributes for Passing Props)
In case there’s a prop name that is the same as a variable name, we can pass it to the component as a shorthand attribute like {message}
below. There is no advantage over using message="{message}"
, but it's more concise.
如果有一个道具名称与变量名称相同,我们可以将其作为速记属性(如下面的{message}
传递给组件。 使用message="{message}"
并没有优势,但是更加简洁。
<!-- Parent.svelte -->
<script>
let message = 'hello child!';
</script>
<Child {message} />
<!-- Child.svelte -->
<script>
let round = true;
</script>
<style>
.round {
border: 1px solid black;
border-radius: 50%;
}
</style>
<button class:round>C</button>
Above, you can see the class:round
attribute getting applied to the button based on if round
is true or false. This could easily become a reusable component where you pass the value of round
from the outside to decide the styling of the component conditionally.
在上方,您可以根据round
为true或false来将class:round
属性应用于按钮。 这很容易成为可重用的组件,您可以在其中从外部传递round
值来有条件地确定组件的样式。
10.内置效果和动画 (10. Built-In Effects and Animations)
Svelte comes pre-packed with powerful effect modules:
Svelte预先包装了功能强大的效果模块:
svelte/motion
effects liketweened
andspring
.svelte/motion
效果,例如tweened
和spring
。svelte/transition
effects likefade
,blur
,fly
,slide
,scale
,draw
.svelte/transition
效果,例如fade
,blur
,fly
,slide
,scale
,draw
。svelte/animate
effects likeflip
.svelte/animate
效果,例如flip
。svelte/easing
effects likebounce
,cubic
,elastic
, and many more.svelte/easing
效果,例如bounce
,cubic
,elastic
等。
There are a few examples in the official Svelte tutorial, but I like this progress bar example the most because of its simplicity.
Svelte官方教程中有一些示例,但是由于它的简单性,我最喜欢此进度条示例。
Animation is an area of web development where you usually look for an external dependency to handle it for you, so it’s great that you can use these right out of the box.
动画是Web开发的一个领域,通常您会寻找一个外部依赖项来为您处理动画,因此,您可以立即使用这些动画,这一点很棒。
合理的理由不采用苗条 (Fair Reasons Not to Adopt Svelte)
To avoid making this article sound like one long fanboy post, these are the cons that I’ve experienced with Svelte so far.
为了避免使这篇文章听起来像是一篇冗长的狂热文章,这些是我到目前为止使用Svelte所经历的缺点。
.svelte
文件无法导出多个组件 (.svelte
files cannot export multiple components)
On one hand, we profit from .svelte
files being default-exported automatically, but this also means that we cannot export multiple components from a single file. I don't think that this is such a big deal since it forces you to follow best practices when writing your application with many small isolated components, which keeps them easy to understand and unit-test.
一方面,我们受益于自动默认导出的.svelte
文件,但这也意味着我们无法从单个文件中导出多个组件。 我认为这没什么大不了的,因为它会迫使您在编写包含许多小隔离组件的应用程序时遵循最佳实践,从而使它们易于理解和进行单元测试。
一般模板语法 (Template syntax in general)
For displaying conditional logic, Svelte uses a syntax that resembles the well-known Handlebars templating syntax.
为了显示条件逻辑,Svelte使用类似于众所周知的Handlebars模板语法的语法。
<script>
let value = 5;
</script>
{#if value > 10}
<p>{value} is greater than 10</p>
{:else}
<p>{value} is smaller than 10</p>
{/if}
I didn’t encounter any issues with this way of writing logic, but I would prefer a more concise syntax.
使用这种逻辑编写方法没有遇到任何问题,但是我希望使用更简洁的语法。
通过export let
在子组件中接收道具 (Receiving props in a child component with export let
)
When you want to pass values from the parent to the child component, you need to pass a value as an attribute and receive it by using export let
with a matching variable name.
如果要将值从父级组件传递到子级组件,则需要将值作为属性传递,并通过使用具有匹配变量名的export let
来接收。
<!-- Parent.svelte -->
<Child message="hello child!" />
<!-- Child.svelte -->
<script>
export let message;
</script>
<p>{message}</p>
In modern JavaScript, export
is usually used as a keyword for exporting a module and let
is used to declare a block-scoped variable, so I feel that the syntax is misusing existing keywords. However, I got used to it and it works well.
在现代JavaScript中, export
通常用作导出模块的关键字,而let
则用于声明块范围的变量,因此我觉得语法在滥用现有关键字。 但是,我已经习惯了,并且效果很好。
发展速度 (Development speed)
This is not directly related to the development experience with Svelte, but you should definitely be aware that Svelte can’t compete (yet) with bigger and sponsored open-source projects like React, Angular, Vue.js, and others in terms of financial support, number of contributors, and popularity as of now.
这与Svelte的开发经验没有直接关系,但是您一定要意识到,Svelte在财务方面还不能与较大的和赞助的开源项目(例如React,Angular,Vue.js等)竞争(目前)。支持,贡献者数量和截至目前的受欢迎程度。
Nevertheless, the community is growing quickly and there is an ever-increasing list of third-party projects built for Svelte by the community, which is available on Made with Svelte. The developers working on Svelte-related tools are geniuses, and you can always ask for help on the Discord channel, Twitter, or Reddit. Svelte also recently added TypeScript support and it works great!
尽管如此,社区正在快速发展,并且社区为Svelte构建的第三方项目列表不断增加,可在Made with Svelte上找到。 使用Svelte相关工具的开发人员都是天才,您可以随时在Discord频道, Twitter或Reddit上寻求帮助。 Svelte最近还添加了TypeScript支持,效果很好!
I like Svelte’s ease of use, small bundle size, and developer experience amongst other factors, so I can accept a slower development speed as a trade-off. If you always need the newest features to be merged as fast as possible, then you might want to look into other available JavaScript frameworks.
我喜欢Svelte的易用性,较小的捆绑包大小以及开发人员的经验以及其他因素,因此我可以接受较慢的开发速度作为折衷方案。 如果您始终需要尽可能快地合并最新功能,则可能需要研究其他可用JavaScript框架。
缺乏可用工作 (Lack of available jobs)
Most companies are still looking for developers who are experienced with the three major front-end frameworks, but there are various, well-known early adopters of Svelte like IBM, Apple, Philips, GoDaddy, 1Password, and The New York Times, just to name a few. You can find an extensive list of companies that are using Svelte at the bottom of the Svelte website.
大多数公司仍在寻找对三个主要前端框架有丰富经验的开发人员,但是Svelte有各种各样的知名早期采用者,例如IBM,Apple,Philips,GoDaddy,1Password和The New York Times ,只是为了仅举几例。 您可以在Svelte网站的底部找到使用Svelte的广泛公司列表。
Usually, the adoption of a new framework takes a while to show up in job offers of companies. Nevertheless, Svelte is fun to learn and many developers enjoy using Svelte — especially for their own personal projects or small-scale applications.
通常,采用新框架需要一段时间才能显示在公司的工作机会中。 尽管如此,Svelte还是很有趣的学习方法,许多开发人员喜欢使用Svelte,尤其是对于他们自己的个人项目或小型应用程序。
结论 (Conclusion)
If a beginner-friendly syntax, a small bundle size output, and an insane performance with Svelte sound great to you, I would recommend you to start hacking away with the Svelte tutorial. The tutorial is really detailed and you can quickly get an understanding of how powerful the framework is.
如果适合初学者使用的语法,较小的捆绑包输出以及Svelte的疯狂表现对您来说听起来很不错,那么我建议您开始学习Svelte教程。 该教程非常详细,您可以快速了解该框架的功能。
Things can definitely change fast in the world of JavaScript frameworks, and I hope you are as convinced as I am that Svelte has all the upsides and potential to make it become the new No. 1 JavaScript front-end framework around!
在JavaScript框架的世界中,事情肯定可以快速改变,我希望您像我一样坚信Svelte具有所有的优势和潜力,使其能够成为周围的新的第一JavaScript前端框架!
Have you worked with Svelte before? How was your experience?
您以前曾与Svelte合作吗? 您的经历如何?
Tell me about it in the comments. I am curious to know.
在评论中告诉我。 我很好奇。
Thanks for reading. I hope you enjoyed it!
谢谢阅读。 我希望你喜欢它!