origin
Last year, I learned about Svelte from a blog post, but I was afraid to try a big project. Recently, I had a small project at hand, and I tried it. I can get started quickly with React or Vue. This article reads the official tutorial API documentation, the default is Vue or React base
Initialize the
Vite 2 now has full support for Svelte and Svelte TS, and you can initialize projects with Vite
# npm 6.x svelte | svelte-ts
npm init @vitejs/app my-vue-app --template svelte-ts
# NPM 7+, additional double horizontal lines are required:
npm init @vitejs/app my-vue-app -- --template svelte-ts
# yarn
yarn create @vitejs/app my-vue-app --template svelte-ts
Copy the code
Svelte components
Svelte’s component file type is.svelte, which is very long, similar to Vue’s single-file component. Svelte components also have three blocks, HTML Script style, and also support pre-processing languages such as the template engine pug. Script supports typescript coffeescript, etc. Similarly style supports SCSS, less, etc. Detailed preprocessor support can be found in the svelte- Preprocess package
export { default as pug } from './processors/pug';
export { default as coffeescript } from './processors/coffeescript';
export { default as typescript } from './processors/typescript';
export { default as less } from './processors/less';
export { default as scss, default as sass } from './processors/scss';
export { default as stylus } from './processors/stylus';
export { default as postcss } from './processors/postcss';
export { default as globalStyle } from './processors/globalStyle';
export { default as babel } from './processors/babel';
export { default as replace } from './processors/replace';
Copy the code
It is simple to use, just like Vue, to add the lang=”” attribute in the tag
<script lang="ts"></script>
<style lang="less"></style>
Copy the code
However, since svelte is precompiled by calling ready-made packages, it is necessary to introduce the corresponding preprocessor when using the preprocessor language. For example, SCSS needs to introduce sass or Nod-Sass, otherwise errors will be reported. The same is true for other languages, as follows
Cannot find any of modules: sass,node-sass Error: Cannot find module 'node-sass' Require stack: - / Users/fengqinglingyu/sevlte/node_modules / _svelte - [email protected] @ svelte - the preprocess/dist/modules/utils js - / Users/fengqinglingyu sevlte/node_modules / _svelte - [email protected] @ svelte - the preprocess/dist/autoProcess. Js - / Users/fengqinglingyu sevlte/node_modules / _svelte - [email protected] @ svelte - the preprocess/dist/index, js - /Users/fengqinglingyu/sevlte/svelte.config.cjsCopy the code
Svelte template
Svelte templates are written in the same way as JSX, with some of the same methods as nunjuck template engines, which are easy to get started with and allow multiple root elements for components
<! JSX type={type} can be abbreviated to {type}, as well as the expansion operator -->
<button {type} {. spreadProps} >
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}</p>
<h1>Hello {name}!</h1>
<p>{a} + {b} = {a + b}.</p>
<! Conditional render -->
{#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}
<! -- List rendering -->
<! -- cats is the original array, the first argument after as is the array item, the second argument is the index of the array item, and the parenthesis is the 'key' property similar to the 'React' list rendering -->
{#each cats as cat, i (i)}
<li><a target="_blank" href="">
{i + 1}: {cat.name}
</a></li>
{/each}
<! -- Asynchronous rendering, similar to FutureBuilder with Flutter -->
{#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
Component state
Variables defined within a component are the state of the component, and if that state changes, the component is rerendered
<script>
let count = 0;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} times
</button>
Copy the code
Component reaction declaration
When certain states of the page change and depend on other states or properties, they can be declared as functions or equations, similar to Vue’s computed properties
<script>
let count = 0;
$: doubled = count * 2;
</script>
<div>{count}</div>
<div>{doubled}</div>
Copy the code
Component External properties
Svelte uses the export keyword to mark variable declarations as properties. Export is not a traditional ES6 export. It is a syntactic notation. Export const export function export class these are read-only attributes of the component and do not accept Svelte values passed from the outside
<! -- Child.svelte -->
<script>
// Properties with no default value
export let answer;
// A property with a default value will use the default value 0 if the parent component does not pass the property
export let count = 0;
// Do not write const, but the component will not accept the value passed in from outside
export const sum = 0;
// If the parent passes 10000, the value is still 0
</script>
<p>The answer is {answer}</p>
<! -- Parent.svelte -->
<script>
import Child from './Child.svelte';
</script>
<Child answer={42} count={1000} sum={10000} />
Copy the code
event
Event binding uses on:eventName, which, like Vue, supports modifiers
<div on:click={increment}>test</div>
<! -- Block default events -->
<div on:click|preventDefault={increment}>test</div>
<! -- Stop events from bubbling -->
<div on:click|stopPropagation={increment}>test</div>
<! -- multi-modifier combination -->
<div on:click|once|preventDefault|stopPropagation={increment}>test</div>
Copy the code
Component life cycle
OnMount onDestoy beforeUpdate afterUpdate onMount onMount onDestoy beforeUpdate afterUpdate onMount The returned function will be executed after the component is destroyed, just like onDestoy
<script>
onMount(() = > {
// The callback that is executed immediately after the component is mounted to the DOM
return () = > {
// Callback to be executed after the component is destroyed, consistent with the onDestroy cycle
}
})
onDestoy(() = > {
// The callback to be executed after the component is destroyed
})
</script>
Copy the code
Use feeling
This time, because it is a small project, I did not try some complex functions of Svelte too much. If I have Vue or React basis, I can get used to it quickly and have some grammar sugar to adapt to. Export const still takes a lot of time, according to normal thinking, the attribute is immutable. But using export const is not. Despite this problem, the overall development experience was pretty good, which is probably why I used fewer features