Saturday, September 11 2021

Svelte, Service Worker and Edgio

Rishi Raj Jain
Rishi Raj Jain @rishi_raj_jain_

Configuring your Svelte app for Edgio

This guide assumes that you're using Webpack with Svelte.

[Optional] Svelte template with Webpack

To create a new project based on this template using degit:

npx degit sveltejs/template-webpack svelte-app
cd svelte-app
npm install

Installation

To install the Edgio CLI run:

npm i -g @edgio/cli

Initialize your project

In the root directory of your project run:

edgio init

This will automatically update your package.json and add all of the required Edgio dependencies and files to your project. These include:

  • The @edgio/core package - Allows you to declare routes and deploy your application on Edgio

  • The @edgio/prefetch package - Allows you to configure a service worker to prefetch and cache pages to improve browsing speed

  • edgio.config.js - A configuration file for Edgio

  • routes.js - A default routes file that sends all requests to Svelte.

Adding Edgio Service Worker

To add service worker to your Svelte app, run the following in the root folder of your project:

npm i process register-service-worker workbox-webpack-plugin

Create service-worker.js at the root of your project with the following:

import { Prefetcher } from '@edgio/prefetch/sw'
import { skipWaiting, clientsClaim } from 'workbox-core'
import { precacheAndRoute } from 'workbox-precaching'

skipWaiting()
clientsClaim()
precacheAndRoute(self.__WB_MANIFEST || [])

new Prefetcher().route()

To register the service worker, first create registerServiceWorker.js in the src folder:

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`/service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
        'For more details, visit https://goo.gl/AFskqB'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

and to include the service worker in the app, edit main.js (in the src folder) as follows:

import './global.css'
import App from './App.svelte'

+ import './registerServiceWorker'

const app = new App({
  target: document.body,
  props: {
    name: 'world',
  },
})

export default app

Now, in webpack.config.js at the root of your project with the following config:

+ const { InjectManifest } = require("workbox-webpack-plugin");
+ const webpack = require('webpack')
....rest of the config
  plugins: [
    + new webpack.ProvidePlugin({
    +   process: 'process/browser',
    + }),
    + new InjectManifest({
    +   swSrc: "./service-worker.js",
    + })
    ...rest of plugins
  ]

Configure the routes

Next you'll need to configure Layer0 routing in the routes.js file. Replace the routes.js file that was created during edgio init with the following:

const { Router } = require('@edgio/core/router')

module.exports = new Router()
  // Send requests to static assets in the build output folder `public`
  .static('public')

  // Send everything else to the App Shell
  .fallback(({ appShell }) => {
    appShell('public/index.html')
  })

The example above assumes you're using Svelte as a single page app. It routes the static assets (JavaScript, CSS, and Images) in the production build folder public and maps all other requests to the app shell in public/index.html.

Run the Svelte app locally on Edgio

Create a production build of your app by running the following in your project's root directory:

npm run build

Run edgio on your local machine:

edgio dev

Load the site: http://localhost:3000

Deploying

Create a Layer0 production build of your app by running the following in your project's root directory:

edgio build && edgio run --production

Next, deploy the build to layer0 by running the following in your project's root directory:

edgio deploy

Write a comment

Email will remain confidential.