Registering Nuxt Plugins: Globally vs Manual Import

Viewed 614

I had made two repositories as plugins where I places my API calls.

plugins/repos/UserRepository.js (I need that in /views/users.vue)

plugins/repos/PostRepository.js (I need that in /views/posts.vue)

To utilize these plugins I have two options:

  1. Register these plugins globally by listing them in the plugins array in nuxt.config.js

  2. Manually import each repo in the respective vue component.

In the case of the first option, my repo looks like this:

export default (ctx, inject) => {

const data={
        getAll(){
            return context.$axios
            .$get("/users");
        }
    }

    inject('userRepo', data);
}

The main advantage of the first approach is I can access the context. But If I manually import it in my component (second approach) then I need to manually pass the context in the plugin.

But the main disadvantage of the first approach is it makes the plugin universally available. So my main question is: is the first one is a bad approach in terms of memory consumption as I don't need PostRepository in users.vue but it still be auto imported by Nuxt because I mentioned it in the plugins array in nuxt.config.js?

Please tell me what's the best way to handle this as I had dozens of repositories so registering all of them globally is a good idea?

1 Answers

You pretty much answered yourself to your question. Memory-wise and also in terms of loading times of your SPA, it will always be better to make a local import rather than having a lot globally even if you only use it 5% of the time.

Then, you can always access the context by itself as usual without needing the plugin aka this.$axios. What would be the blocking use-case here?

If you're working with Nuxt3, you could also use composables.

Related