Chapter 2: Setting Up Svelte

In this chapter, we'll guide you through setting up your Svelte development environment. We'll install the necessary tools and create your first Svelte project using Vite, a modern build tool optimized for speed.

Installing Node.js and npm

Before creating a Svelte project, you need to install Node.js, which includes npm (Node Package Manager).

Steps:

  1. Visit nodejs.org and download the LTS (Long-Term Support) version.
  2. Follow the installation wizard for your operating system (Windows, macOS, or Linux).
  3. Open a terminal and verify the installation:
    node --version
    npm --version

Creating a Svelte Project

The easiest way to create a Svelte project is using Vite with the Svelte template.

Steps:

  1. Open your terminal and run:
    npm create vite@latest my-svelte-app -- --template svelte
  2. Navigate into your project:
    cd my-svelte-app
  3. Install dependencies:
    npm install
  4. Start the development server:
    npm run dev
  5. Open your browser and navigate to http://localhost:5173 to see your project running.

Project Structure Overview

After creating your project, you'll see the following structure:

my-svelte-app/
├── src/
│   ├── App.svelte       # Root component
│   ├── main.js          # Entry point
│   └── components/      # Reusable components
├── public/              # Static assets
├── index.html           # HTML template
├── package.json         # Project metadata and dependencies
├── vite.config.js       # Vite configuration
└── svelte.config.js     # Svelte configuration

Key Files:

  • src/App.svelte: Your main component. This is where you'll build your application.
  • src/main.js: The entry point that mounts the App component to the DOM.
  • index.html: The HTML template file that includes your Svelte app.
  • package.json: Defines your project dependencies and scripts.

Useful npm Scripts

Your package.json includes helpful scripts for development:

  • npm run dev - Start the development server with hot module replacement.
  • npm run build - Build your project for production.
  • npm run preview - Preview your production build locally.

Now that your environment is set up, you're ready to start building Svelte components!

Next: Chapter 3 - Svelte Basics