How do you use Svelte with static site generation

How do you use Svelte with static site generation

Static Site Generation (SSG) has become increasingly popular due to its ability to deliver fast, secure, and SEO-friendly websites. Svelte, with its lightweight and efficient approach to building user interfaces, is a great match for SSG. In this article, we will explore how to use Svelte with static site generation to create a performant, scalable, and maintainable web application.

Introduction to Static Site Generation

Static Site Generation (SSG) involves pre-rendering pages at build time, resulting in static HTML files that can be served directly to the client. This approach offers several benefits:

  • Performance: Pre-rendered HTML is served instantly without the need for server-side processing.
  • Security: Static sites are less prone to security vulnerabilities as there are no server-side components.
  • SEO: Search engines can easily crawl and index static HTML.
  • Scalability: Static sites can be deployed on CDNs, ensuring high availability and low latency.

Setting Up a Svelte Project with SSG

To get started with Svelte and SSG, we’ll use SvelteKit, a framework for building Svelte applications with support for server-side rendering, SSG, and more.

Step 1: Create a New SvelteKit Project

  1. Initialize a new SvelteKit project:

    npm init svelte@next svelte-ssg
    cd svelte-ssg
    
  2. Install the dependencies:

    npm install
    
  3. Run the development server:

    npm run dev
    

Step 2: Configure SvelteKit for Static Site Generation

SvelteKit supports SSG out of the box. We need to configure the svelte.config.js file to use the adapter for static site generation.

  1. Install the adapter-static:

    npm install @sveltejs/adapter-static
    
  2. Update svelte.config.js to use the static adapter:

    // svelte.config.js
    import adapter from '@sveltejs/adapter-static';
    
    export default {
      kit: {
        adapter: adapter({
          // default options are shown
          pages: 'build',
          assets: 'build',
          fallback: null
        })
      }
    };
    

Creating Pages with SvelteKit

SvelteKit uses a file-based routing system where the file structure in the src/routes directory maps to the URL structure of the application.

Step 1: Create a Home Page

  1. Create a src/routes/index.svelte file:

    <!-- src/routes/index.svelte -->
    <script>
      export let data;
    </script>
    
    <h1>Welcome to Svelte with Static Site Generation</h1>
    <p>This is the home page.</p>
    
  2. Generate the static files:

    npm run build
    

    This command will generate static HTML files in the build directory.

Step 2: Create a Blog Page with Dynamic Routes

Static sites often have dynamic content, such as blog posts. SvelteKit allows you to create dynamic routes using the [param] syntax.

  1. Create a src/routes/blog/[slug].svelte file:

    <!-- src/routes/blog/[slug].svelte -->
    <script context="module">
      export async function load({ params }) {
        const { slug } = params;
        const posts = {
          'first-post': {
            title: 'First Post',
            content: 'This is the first post.'
          },
          'second-post': {
            title: 'Second Post',
            content: 'This is the second post.'
          }
        };
        return {
          props: {
            post: posts[slug]
          }
        };
      }
    </script>
    
    <script>
      export let post;
    </script>
    
    <h1>{post.title}</h1>
    <p>{post.content}</p>
    
  2. Create a list of blog posts in src/routes/blog/index.svelte:

    <!-- src/routes/blog/index.svelte -->
    <script>
      const posts = [
        { slug: 'first-post', title: 'First Post' },
        { slug: 'second-post', title: 'Second Post' }
      ];
    </script>
    
    <h1>Blog</h1>
    <ul>
      {#each posts as post}
        <li><a href={`/blog/${post.slug}`}>{post.title}</a></li>
      {/each}
    </ul>
    
  3. Generate the static files:

    npm run build
    

    SvelteKit will generate static HTML files for the blog index and each blog post.

Fetching Data from an API

In real-world applications, data is often fetched from an external API. SvelteKit makes it easy to fetch data during the build process.

  1. Create a src/routes/api/posts.js file to simulate an API endpoint:

    // src/routes/api/posts.js
    export async function get() {
      const posts = [
        { slug: 'first-post', title: 'First Post', content: 'This is the first post.' },
        { slug: 'second-post', title: 'Second Post', content: 'This is the second post.' }
      ];
      return {
        status: 200,
        body: posts
      };
    }
    
  2. Fetch data in the load function of src/routes/blog/index.svelte:

    <!-- src/routes/blog/index.svelte -->
    <script context="module">
      export async function load() {
        const response = await fetch('/api/posts');
        const posts = await response.json();
        return {
          props: {
            posts
          }
        };
      }
    </script>
    
    <script>
      export let posts;
    </script>
    
    <h1>Blog</h1>
    <ul>
      {#each posts as post}
        <li><a href={`/blog/${post.slug}`}>{post.title}</a></li>
      {/each}
    </ul>
    
  3. Fetch data in the load function of src/routes/blog/[slug].svelte:

    <!-- src/routes/blog/[slug].svelte -->
    <script context="module">
      export async function load({ params }) {
        const response = await fetch('/api/posts');
        const posts = await response.json();
        const post = posts.find(post => post.slug === params.slug);
        return {
          props: {
            post
          }
        };
      }
    </script>
    
    <script>
      export let post;
    </script>
    
    <h1>{post.title}</h1>
    <p>{post.content}</p>
    
  4. Generate the static files:

    npm run build
    

Deploying a Svelte Static Site

Once the static files are generated, you can deploy your site to any static hosting service, such as Vercel, Netlify, or GitHub Pages.

Deploying to Vercel

  1. Install the Vercel CLI:

    npm install -g vercel
    
  2. Deploy your site:

    vercel
    

Deploying to Netlify

  1. Install the Netlify CLI:

    npm install -g netlify-cli
    
  2. Deploy your site:

    netlify deploy --dir=build
    

Deploying to GitHub Pages

  1. Install the gh-pages package:

    npm install --save-dev gh-pages
    
  2. Add deployment scripts to package.json:

    "scripts": {
      "predeploy": "npm run build",
      "deploy": "gh-pages -d build"
    }
    
  3. Deploy your site:

    npm run deploy
    

Conclusion

Using Svelte with Static Site Generation provides an excellent way to build fast, secure, and SEO-friendly websites. SvelteKit makes it easy to configure and generate static sites with its powerful features and straightforward setup. By following the steps outlined in this article, you can create a Svelte-based static site, fetch data from APIs, and deploy your site to popular hosting services. Embrace the power of Svelte and SSG to deliver high-performance web applications.

How do I install Tailwind CSS in my project

How do I integrate Tailwind CSS with a JavaScript framework like React or Vue.js

How do I create a responsive layout with Tailwind CSS

How do I vertically center an element in Tailwind CSS

How do I customize the spacing like padding and margin between elements in Tailwind CSS