Because my level is limited, there are any problems or mistakes we can go to my blog correction, thank you.
Introduction to the
- Less code
- No Virtual DOM
- True responsiveness
Svelte is an entirely new approach to building user interfaces. While most of the work of traditional frameworks like React and Vue is done in the browser, Svelte translates that work into compilation steps, which happens when you build your application. Instead of using techniques like Virtual DOM Diffing, Svelte writes code that updates the DOM in a specific way when your application’s state changes.
Svelte website
After reading the description on the website, we may still not understand what is different about this framework.
Here’s what yuxi said to Svelte (although utahs said this when Svelte was v1 or V2, not too much difference between v1 and V2. However, the Ractive API design has been completely abandoned in version 3, and v3 has been greatly changed.) The point of continuing to quote this paragraph is that this is the core idea of Svelte.
By Rich Harris, author of Ractive, Rollup, and Buble, the wheelie of the front-end world, and now the wheel!
The API design of this framework is inherited from Ractive (and certainly very similar to Vue), but that’s beside the point. The core idea of Svelte is to “reduce the amount of code at runtime through static compilation”. For example, the current framework, whether React Angular or Vue, no matter how you compile it, must “import” the framework itself, which is called the Runtime. But with Svelte, once a Svelte component is compiled, all the required runtime code is included in it. You don’t need to introduce a so-called framework runtime other than the component itself!
So Svelte is similar to vue.js Javascript frameworks. ‘traditional’ frameworks require runtime code (current frameworks, whether React or VueJS, no matter how you compile them, will necessarily introduce the framework itself when used) to define and execute modules and maintain state. Update the view and also run the frames. Svelte is completely embedded in JavaScript. As if there is no reference to the framework, this approach is mainly beneficial to the file size.
The framework is really a tool that compiles your source code into pure JavaScript with no dependencies. You can compile the source using Webpack, Browserify, Rollup, or Gulp, and Svelte provides plug-ins for that.
With this introduction, I’m going to write a simple demo to experience the syntax of the framework by introducing the commonly used UI component library Sveltestrap (Bootstrap’s Svelte component library) and Echarts.
Simple experience
Create the Svelte project
npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm run dev
Copy the code
Visit localhost:5000 to see the initial page of svelte.
Lifecycle hook
onMount
OnMount will run the callback as soon as the component is mounted to the DOM. Note that onMount does not run in the server-side component.
<script>
import { onMount } from 'svelte';
onMount((a)= > {
console.log('the component has mounted');
});
</script>
Copy the code
If a function is returned from onMount, it is called when the component is unmounted.
<script>
import { onMount } from 'svelte';
onMount((a)= > {
const interval = setInterval((a)= > {
console.log('beep');
}, 1000);
return (a)= > clearInterval(interval);
});
</script>
Copy the code
beforeUpdate
The callback function runs immediately after any state changes and before the component updates. The first callback will be before the initial onMount.
<script>
import { beforeUpdate } from 'svelte';
beforeUpdate((a)= > {
console.log('the component is about to update');
});
</script>
Copy the code
afterUpdate
Run the callback immediately after the component is updated.
<script>
import { afterUpdate } from 'svelte';
afterUpdate((a)= > {
console.log('the component just updated');
});
</script>
Copy the code
onDestroy
Run the callback after the component is unloaded. Among onMount, beforeUpdate, afterUpdate, and onDestroy, this is the only component that runs in a server-side component.
<script>
import { onDestroy } from 'svelte';
onDestroy((a)= > {
console.log('the component is being destroyed');
});
</script>
Copy the code
An introduction to svelte syntax
1. Basic grammar
Data binding
<script>
let name = 'world';
</script>
<h1>Hello {name}!</h1>
Copy the code
Just as you can use curly braces to control text, you can use curly braces to control element attributes.
<script>
let src = 'tutorial/image.gif';
let name = 'Rick Astley';
</script>
<img {src} alt="{name} dances.">
Copy the code
Just as in HTML, you can add tags to components. Let’s add some styles to the element:
<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>
<p>This is a paragraph.</p>
Copy the code
Create components
Svelte component names are capitalized to avoid confusion with HTML custom tags and the like.
// Nested.svelte
<p>This is another paragraph.</p>
// App.svelte
<script>
import Nested from './Nested.svelte';
</script>
<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>
<p>This is a paragraph.</p>
<Nested/>/ / the capitalCopy the code
2. The response
At the heart of Svelte is a powerful reaction system for keeping the DOM in sync with application state (for example, in response to an event).
<script>
let count = 0;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Copy the code
Svelte automatically updates the DOM when a component’s state changes. Often, some part of a component’s state needs to be computed from other parts (such as full names derived from firstName and lastName) and recalculated or run arbitrary statements when it changes.
<script>
let count = 0;
$: doubled = count * 2;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}</p>
Copy the code
<script>
let count = 0;
$: if (count >= 10) {
alert(`count is dangerously high! `);
count = 9;
}
function handleClick() {
count += 1;
}
</script>
Copy the code
Note: Svelte’s response is based on assignment, so we don’t update push,splice, etc. So when we encounter these operations we can do an extra assignment to trigger the response.
3. The value
In any real-world application, data needs to be passed from one component to its children. To do this, we need to declare the property, usually abbreviated to ‘props’. In Svelte, we use the export keyword to do this.
// App.svelte
<script>
import Nested from './Nested.svelte';
</script>
<Nested answer={42} />
// Nested.svelte
<script>
export let answer; Export let answer = '2234';
</script>
<p>The answer is {answer}</p> // The answer is 42
Copy the code
If you have a property object, you can “extend” them to a component instead of specifying them one by one:
// App
<script>
import Info from './Info.svelte';
const pkg = {
name: 'svelte'.version: 3.speed: 'blazing'.website: 'https://svelte.dev'
};
</script>
<Info {. pkg} / >
// Info
<script>
export let name;
export let version;
export let speed;
export let website;
</script>
<p>
The <code>{name}</code> package is {speed} fast.
Download version {version} from <a href="https://www.npmjs.com/package/{name}">npm</a>
and <a href={website}>learn more here</a>
</p>
Copy the code
4. Logical processing
If – else judgment
<script>
let x = 7;
</script>
{#if x > 10}
<p>{x} is greater than 10</p>
{:else if 5 > x}
<p>{x} is less than 5</p>
{:else}
<p>{x} is between 5 and 10</p>
{/if}
Copy the code
Each traversal
If we need to iterate over a list of data, we can use the each block:
<ul>
{#each cats as cat}
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
{cat.name}
</a></li>
{/each}
</ul>{#each cats as cat, I}<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
{i + 1}: {cat.name}
</a></li>{#each cats as {id, name}, I}<li><a target="_blank" href="https://www.youtube.com/watch?v={id}">
{i + 1}: {name}
</a></li>
{/each}
Copy the code
The problem with this is that when we change the data, it causes everything to refresh again. So, we specify a unique identifier for each block.
{#each things as thing (thing.id)}
<Thing current={thing.color}/>
{/each}
Copy the code
Asynchronous processing
Most Web applications must deal with asynchronous data at some point. Svelte makes it easy to wait for a promise value directly in the tag
<script>
let promise = getRandomNumber();
async function getRandomNumber() {
const res = await fetch(`tutorial/random-number`);
const text = await res.text();
if (res.ok) {
return text;
} else {
throw new Error(text); }}function handleClick() {
promise = getRandomNumber();
}
</script>
<button on:click={handleClick}>
generate random number
</button>
{#await promise}
<p>. waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
Copy the code
5. Events
Dom events
Dom events are bound using the ON: directive.
<script>
function handleClick(event) {
alert('hello')}</script>
<div on:click={handleClick}>
button
</div>
Copy the code
Some frameworks do not allow inline events for performance purposes, but Svelte supports inline syntax.
<div on:click="{e => alert(' hello ')}">// It can be left out of quotes, just to distinguish the syntax of a button</div>
Copy the code
Dom events also support the use of modifiers, such as the once modifier, which means that they are called only once.
<div on:click|once="{e => alert(' hello ')}">
button
</div>
Copy the code
Common with the self, except once the preventDefault, stopPropagation, passive, the capture modifiers, such as specific reference documentation. And modifier also supports connection, on: click | once | the capture = {… }.
Component events
Events are dispatched within the component with the help of an event distribution mechanism.
But we must call createEventDispatcher when the component is first instantiated, and we cannot do this internally later, for example in the setTimeout callback.
// App
<script>
import Outer from './Outer.svelte';
function handleMessage(event) {
alert(event.detail.text);
}
</script>
<Outer on:message={handleMessage}/>
Copy the code
// Inner
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function sayHello() {
dispatch('message', {
text: 'Hello! '
});
}
</script>
<button on:click={sayHello}>
Click to say hello
</button>
Copy the code
Unlike DOM events, Outer component events do not bubble. If you want to listen for an event on a deeply nested component, the intermediate component must forward the event. But the intermediate components need to do repeated event distribution, so svelte provides us with a shorthand, without a value, for forwarding.<script>
import Inner from './Inner.svelte';
</script>
<Inner on:message/>
Copy the code
Dom events also support forwarding, of course.
<button on:click>
Click me
</button>
Copy the code
This is just a brief introduction to some simple syntax, but more in-depth events, methods, such as slot, can be read in the official documentation.
Analysis of the
Of course, everything has advantages, there must be disadvantages. This part of the analysis is based on the superficial personal basis and some third party reference articles. If there are any problems or mistakes, please kindly excuse and help correct them. Thank you very much!
Why svelte?
- You work alone or in a small team, so it’s easy to get started and great for small projects.
- You care about the size of the bundle.
- You start writing JS code on the front end, and Svelte lets you code freely without having to learn JSX or TS, etc. Return the front end to its original form.
Why not use Svelte?
- You won’t find UI components out of the box, ecologically small.
- Sometimes there are implicit errors.
- If you think your project will need a mobile application in the future. You have “Svelte Native,” which is based on NativeScript. But at present, its use effect is not too optimistic.
- You should write strict naming and coding conventions for your team, because the Svelte tutorial won’t do that for you, so you’ll end up with a very complex code base. Use in large projects needs to be validated.
Compare with other frameworks
In fact, svelte is more like a compiler, while others are more like frameworks or libraries. (Personally, REACT and Vue are more like libraries. Because Angular has a complete development architecture and pattern that covers everything from form validation to HTTP (big and complete), React and Vue focus purely on components and interfaces (lightweight, small and sophisticated). Of course, they are constantly updated, borrowed and expanded).
Svelte | React | Angular | Vue | |
---|---|---|---|---|
type | More like a compiler | library | The framework | Library or framework |
packaging | Minimal, quick pack | Small, quick pack | Medium size, quick to pack | Small, quick pack |
API | The core function | The core function | Huge feature set | Medium size feature set |
Maturity and Market | New framework, popular but not widely adopted | Mature, popular and most used | Mature and popular | Relatively mature and very popular (our country is very warm) |
The background | personal | It started with individuals and now the entire open source community collectively | ||
Common ecological | Svelte Native | RN, React VR, and so on | Ionic, etc. | Vant, vux, etc |
Use of third Party projects
The introduction of sveltestrap
download
npm install --save sveltestrap
npm install --save bootstrap
Copy the code
The introduction of CSS
After downloading the component library and bootstrap, we need to import the bootstrap style file in SRC /main.js.
import App from './App.svelte';
import 'bootstrap/dist/css/bootstrap.min.css';
const app = new App({
target: document.body,
props: {
name: 'world'}});export default app;
Copy the code
The default packaging tool (rollup.js) in Svelte is not configured to handle CSS imports.
Note that you need plugins to import files that are not JavaScript
Here we need to use the rollup CSS plugin postcss:
npm install --save-dev rollup-plugin-postcss
'or'
yarn add rollup-plugin-postcss --dev
Copy the code
Fill in the configuration in rollup.config.js:
import postcss from 'rollup-plugin-postcss'; . exportdefault {
plugins: [
postcss({
extensions: [ '.css'],}),]};Copy the code
use
Make changes in SRC/app.svelte:
<script>
import {
Button,
Modal,
ModalBody,
ModalFooter,
ModalHeader
} from "sveltestrap";
let open = false;
const toggle = (a)= >(open = ! open);</script>
<main>
<Button on:click={toggle}>Open!</Button>
<Modal isOpen={open} {toggle} >
<ModalHeader {toggle} >test</ModalHeader>
<ModalBody>I'm the modal box</ModalBody>
<ModalFooter>
<Button color="primary" on:click={toggle}>Do Something</Button>
<Button color="secondary" on:click={toggle}>CancBl</Button>
</ModalFooter>
</Modal>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none; }}</style>
Copy the code
The introduction of echarts
// Download NPM install echarts --save // app.svelte<script>
import {
Button,
Modal,
ModalBody,
ModalFooter,
ModalHeader
} from "sveltestrap";
import Chart from "./chart.svelte";
let open = false;
const toggle = (a)= >(open = ! open);</script>
<main>
<Button on:click={toggle}>Open!</Button>
<Modal isOpen={open} {toggle} >
<ModalHeader {toggle} >test</ModalHeader>
<ModalBody>
<Chart />
</ModalBody>
<ModalFooter>
<Button color="primary" on:click={toggle}>Do Something</Button>
<Button color="secondary" on:click={toggle}>CancBl</Button>
</ModalFooter>
</Modal>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none; }}</style>
// chart.svelte
<script>
import echarts from "echarts";
import { onMount } from "svelte";
// Initializes the echarts instance based on the prepared DOM
onMount((a)= > {
const myChart = echarts.init(document.getElementById('main'));
// Specify the chart configuration items and data
var option = {
title: {
text: "Getting started with ECharts"
},
tooltip: {},
legend: {
data: ["Sales"]},xAxis: {
data: ["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"]},yAxis: {},
series: [{name: "Sales".type: "bar".data: [5.20.36.10.10.20]]}};// Display the chart using the configuration items and data you just specified.
myChart.setOption(option);
});
</script>
<style>
</style>
<div id="main" style="width: 500px; height:400px;" />
Copy the code