Scaffolding our project
Now that all the prerequisites are in place, we're ready to start coding:
- Create an empty folder where you want to put your application's code. In this book, we'll place the code in a folder called
svelte-poc
inside our home directory. - Open this folder in Visual Studio Code, or your preferred editor.
- Because our Svelte application relies on Node.js and NPM, initialize the project by creating a
package.json
file.If you have the NPM extension installed in Visual Studio Code, you can launch the command palette with Ctrl + Shift + P (or Command + Shift + P on a Mac) and then write
> npm run init
and press Return.Alternatively, using a terminal (tip: you can press Ctrl + `, or Command + ` on a Mac, to launch an integrated terminal in Visual Studio Code ; where ` is the backtick), run the following command:
npm init
In both cases, you will be asked to provide some details about your project. At this stage, it's probably safe to accept all defaults by keep pressing the Return key until done.
- Finally, we will need to create two folders inside our project:
(a)
src
, which contains our application's source(b)
public
, which will contain the compiled, bundled code:
Using a bundler
Writing web applications with Svelte requires the use of a bundler, which merges all JavaScript code into a single file. Not only do they provide convenient features, such as code minification and tree shaking (removing unused code and dependencies), but they also compile Svelte components into executable code. As you will recall from the introduction, in fact, Svelte apps need to be compiled, and that's how Svelte helps to generate small and fast web applications.
The Svelte community is somehow split between two bundlers: Rollup, which also happens to have been originally created by the same Rich Harris who built Svelte, and Webpack. In this book, we're going to make an opinionated choice and use Webpack.
Webpack is arguably the most popular bundler for JavaScript applications. It comes with a host of advanced features (for example, support for code splitting) and a vast number of plugins. Because of its popularity, it's easy to find modules, plugins, documentation, and suchlike, and there's a vibrant community that can provide support. Lastly, using Webpack can allow easier integrations with existing systems. The downside is that Webpack's flexibility makes it a bit more complex, but this book's instructions can help you navigate that complexity.