How to add Nprogress to SvelteKit

How to add Nprogress to SvelteKit

Written by Posandu Mapa on Mar 18th, 2023 Views Report Post

You may be wondering how to add Nprogress to SvelteKit. This is a simple guide to help you get started.

Step 1: Install Nprogress

We first need to install nprogress to SvelteKit. To do this, we can run the following command:

npm install nprogress # or pnpm install nprogress or yarn add nprogress

Step 2: Modify the layout

We need to modify the layout to add the nprogress bar. Create or modify the layout file in src/routes/+layout.svelte to add the following code:

<script>
    import "nprogress/nprogress.css";
    import NProgress from "nprogress";
      import { navigating } from "$app/stores";


    NProgress.configure({
        // Full list: https://github.com/rstacruz/nprogress#configuration
        minimum: 0.16,
    });

    $: {
        if ($navigating) {
            NProgress.start();
        } else NProgress.done();
    }
</script>

Here we are importing the nprogress css and the nprogress library. We are also importing the navigating store from the app store. We are then configuring the nprogress bar. We are then using a $: block to check if the user is navigating. If they are, we start the nprogress bar. If they are not, we stop the nprogress bar.

Typescript

Here is the typescript version of the above code:

<script lang="ts">
    import "nprogress/nprogress.css";
    import NProgress from "nprogress";
    import { navigating } from "$app/stores";

    NProgress.configure({
        // Full list:
        minimum: 0.16,
    });

    $: {
        if ($navigating) {
            NProgress.start();
        } else NProgress.done();
    }
</script>

Make sure to add the lang="ts" attribute to the script tag. And also install the typescript types for nprogress:

npm install @types/nprogress # or pnpm install @types/nprogress or yarn add @types/nprogress

Conclusion

That's it! You now have nprogress added to your SvelteKit app. You can now navigate around your app and see the nprogress bar.

Comments (0)