Adding NProgress to a Svelte + Sapper project

5 May 2020

Sapper is dead. Check this article by Posandu Mapa for the SvelteKit version.

NProgress greatly improves the UX of single-page app (SPA) projects. I procrastinated on adding it to my Sapper projects because I wasn’t able to find a how-to online.

Turns out, making it work is pretty straightforward. Let’s get on with it.

Setting up the project

Follow Sapper’s getting started doc to scaffold our new project.

TerminalShell
npx degit "sveltejs/sapper-template#rollup" my-app
cd my-app
npm install

Add NProgress to our list of dependencies and start the server.

TerminalShell
npm install nprogress
npm run dev

Wiring up NProgress

The JavaScript part

Start by hooking up NProgress with Sapper’s preloading state. We do this inside the script tag of our root _layout.svelte.

Note: do not confuse this preloading boolean with the preload function that’s used for data loading.

src/routes/_layout.svelteSvelte
<script>
	import NProgress from 'nprogress'
	import { stores } from '@sapper/app'
	import Nav from '../components/Nav.svelte'

	NProgress.configure({
		// Pass in your configuration here, below is just how I like it
		// Full list: https://github.com/rstacruz/nprogress#configuration
		minimum: 0.16,
		showSpinner: false,
	})

	const { preloading } = stores()

	$: {
		if ($preloading) {
			NProgress.start()
		}

		if (!$preloading) {
			NProgress.done()
		}
	}

	export let segment
</script>

<!-- … rest of file … -->

The CSS part

Navigate to node_modules/nprogress/nprogress.css and copy its content, then paste it anywhere inside of static/global.css.

That’s it. NProgress should now work inside of your app. Feel free to edit the CSS you just copied to play around with how it looks.

Extras

If you have Svelte preprocess set up, you might be able to import the CSS this way:

src/server.jsJavaScript
import 'nprogress/nprogress.css'
// … rest of file …

The next how-to post will be on setting up Tailwind CSS with Sapper, which includes setting up PostCSS as Svelte preprocess. It’ll let us refactor the way our NProgress CSS is wired up.

Update: Tailwind post is up.

Closing words

Hit me up on Twitter @ryanditjia if you need help, or know a better way of setting this up. Also happy to talk about Svelte, Elixir + Phoenix, typography, and web development in general.