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:
- Visit nodejs.org and download the LTS (Long-Term Support) version.
- Follow the installation wizard for your operating system (Windows, macOS, or Linux).
- 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:
- Open your terminal and run:
npm create vite@latest my-svelte-app -- --template svelte - Navigate into your project:
cd my-svelte-app - Install dependencies:
npm install - Start the development server:
npm run dev - Open your browser and navigate to
http://localhost:5173to 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