如何開始使用Svelte
自從我開始使用Hugo作為創建網站的靜態網站生成器以來,與過去使用CMS動態生成頁面的CMS相比,我已經越來越喜歡這種在Web上發布的方法。
Svelte是一個給我同樣感覺的JavaScript框架。與React,Vue,Angular和其他框架相比,使用Svelte構建的應用程序是已編譯事先,不必為網站訪問者提供框架和庫代碼,因此,所有體驗的結果都更加流暢,佔用的帶寬更少,並且一切感覺更快,更輕便。
與Hugo一樣,Hugo會在部署時消失並生成純HTML,Svelte也會消失,而您所獲得的只是純JavaScript。
但是,讓我們跳到本文的重點。如何開始使用Svelte。
您需要安裝Node.js。看看我的如何安裝Node.js發布(如果您還沒有的話)!
並確保它是最新版本(如何更新Node.js)。
節點安裝npx
命令,這是運行Node命令的便捷方法。特別是,我們將運行以下代碼:
npx degit sveltejs/template firstapp
這將下載並運行degit命令,依次下載位於以下位置的Svelte項目模板的最新代碼https://github.com/sveltejs/template, 進入firstapp
文件夾。
現在進入firstapp
文件夾並運行npm install
下載模板的其他依賴項。在撰寫本文時,這些是該項目模板的依賴項:
"npm-run-all"
"rollup"
"rollup-plugin-commonjs"
"rollup-plugin-livereload"
"rollup-plugin-node-resolve"
"rollup-plugin-svelte"
"rollup-plugin-terser"
"svelte"As you can see, it’s the Svelte core, plus Rollup (a Webpack alternative) and some of its plugins. Plus npm-run-all
, a CLI tool that is used to run multiple npm scripts in parallel, or sequential.
We’re now ready to run our Svelte site in development mode, by running
npm run dev
This will start the app on localhost, on port 5000, by default:

If you point your browser there, you’ll see the “Hello world!” example:

You’re now ready to open the code in your favorite editor. The src
folder contains all you need to tweak the app: the main.js
file:

This file is the entry point and in this case initializes the App component, which is defined in App.svelte
, a single file component:
<script>
export let name;
</script>
<style>
h1 {
color: purple;
}
</style>
<h1>Hello {name}!</h1>
If you are familiar with Vue.js, it’s a similar concept. You define the markup, the style and the JavaScript for each component in a single .svelte
file.
Download my free Svelte Handbook
More svelte tutorials:
- Getting started with Svelte - a short tutorial
- How to work with props in Svelte
- How to import components in Svelte
- How to export functions and variables from a Svelte component
- Svelte templates: conditional logic
- How to rerender a Svelte component on demand
- Svelte Slots
- How to add comments in Svelte templates
- Svelte Bindings
- Handling State Updates in Svelte
- Reactive Statements in Svelte
- Svelte Lifecycle Events
- Svelte templates: loops
- Resolve promises in Svelte templates
- Working with events in Svelte
- Cross-component State Management in Svelte
- How to access a URL parameter in Sapper outside of script module
- How to dynamically apply CSS in Svelte
- How to redirect to a URL in Sapper
- How to simulate a for loop in Svelte templates