DEV Community

Fazail Alam
Fazail Alam

Posted on • Originally published at codef.site on

How to create plugin in nuxt3

"nuxt3 plugin example"
In this tutorial, we will learn how to create a plugin in nuxt3. we will use some app hooks to create a plugin. With the help of these hooks, we will create a plugin that will show a progress bar on the top of the page.

Prerequisites

We will use NProgress package to show the bar at the top of page while the page is loading. So lets install it. And make sure to import its css or add a link to its css file.

npm install --save nprogress
Enter fullscreen mode Exit fullscreen mode
<link rel="stylesheet" href="https://unpkg.com/nprogress@0.2.0/nprogress.css">
Enter fullscreen mode Exit fullscreen mode

Create a plugin

Now create a folder called /plugins in the root of your project. And create a file called page-progress.js in this folder. You can name the whatever you want. Nuxt provides a helper function to create a plugin called defineNuxtPlugin.

export default defineNuxtPlugin((nuxtApp) => {
    ...
})
Enter fullscreen mode Exit fullscreen mode

Inside this function, we will use the nuxtApp object to access hooks and show/hide the progress bar. We need two hooks i.e. page:start and page:finish.

  1. page:start - This hook will be called when the page starts loading.
  2. page:finish - This hook will be called when the page finishes loading.

First we import NProgress package and then call the NProgress.start() method in page:start hook to start showing the progress bar. And in page:finish hook, we will call the NProgress.done() method to hide the progress bar.

import NProgress from "nprogress";

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.hooks.hook("page:start", () => {
        NProgress.start();
    });
    nuxtApp.hooks.hook("page:finish", () => {
        NProgress.done();
    });
});
Enter fullscreen mode Exit fullscreen mode

By default NProgress will show spinner at the top-right of the page and to disable it we need pass showSpinner to false.

export default ...
NProgress.configure({ showSpinner: false })
nuxtApp.hooks....
Enter fullscreen mode Exit fullscreen mode

We don't need to register our plugin in the plugins array in the nuxt config because nuxt will automatically register the plugin.

Top comments (1)

Collapse
 
softlaza profile image
SoftLaza

is it working normaly on SSR mode