appendix E A very brief introduction to Svelte
This appendix covers
- Recognizing the structure of a Svelte file
- Sharing information between components
- Adding rendering logic
- Using reactive variables and functions
This appendix provides an overview of Svelte, a JavaScript library that is popularly used in combination with D3.js. If you aren’t familiar with Svelte, this appendix will give you the knowledge you need to follow along with the projects from chapters 14 and 15.
E.1 The structure of a Svelte file
Svelte files can be recognized by their .svelte
extension. By convention, their name starts with an uppercase letter. Svelte files are made of three sections: the script, the markup, and the styles. At the top of the file, the <script>
tags contain any JavaScript code you need for the component. This is where you’ll run your D3 code. Then we add our markup, such as the <div>
tag in the following snippet. Note how we can dynamically use JavaScript variables within the markup by including them between curly braces ({}
). Finally, we complete the component with the <style>
tags, in between which you can add CSS styles targeting the component’s elements. Note that scripts and styles are scoped to the component in which they are declared and won’t affect other components. In addition, a component doesn’t have to include those three sections; they are all optional. You could have a static component with markup and styles or one that only contains logic: