Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a library to be available in whole Vue.js 3 project?

Tags:

vue.js

vuejs3

According to this blog post the correct way of including frequently used libraries (e.g. axios) in Vue.js 2 is to set them as property of Vue prototype object like this:

import axios from 'axios';
Object.defineProperty(Vue.prototype, '$axios', { value: axios });

Unfortunately, this approach is not working in Vue.js 3 anymore. So what is the correct way of importing library to be accesible in whole project? I would prefer not to set them as global variable (i.e. to the window object.)

like image 205
Miroslav Valcicak Avatar asked Sep 29 '20 11:09

Miroslav Valcicak


People also ask

How do I add a JavaScript library to a VUE project?

The cleanest and most robust way to use a JavaScript library in a Vue project is to proxy it to a property of the Vue prototype object. Let's do that to add the Moment date and time library to our project: entry.js. import moment from 'moment';

Can I use external libraries in Vue?

It can be useful to create a Vue plugin that wraps an external library to make it easier to use in a Vue app, but it’s not necessary. You should skip this step until you have understood how to import a library on its own, as explained above.

How to globally register components in a VUE 3 project?

We’re now going to create a Vue 3 plugin that will globally register the components from your library in a consuming project. At the top of the file, we will import the registered components. Then, in the plugin install method, we’ll iterate the components object and globally register each component on the Vue instance.

Can We import a Vue store from another Vue project?

Like in an vue-cli-created project, the default store.js contains an import: import Vuex from 'vuex' where no specific path is declared. Yes, we can. I used to have this: import {Howl, Howler} from 'howler'; and both work.


2 Answers

To use provide/inject as an alternative

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios';
    
const app = createApp(App)
app.provide('axios', axios ) // <-- define here
app.mount('#app')

Then in any component you wanna use axios you would do this

app.component('todo-list-statistics', {
  inject: ['axios'],
  created() {
    this.axios // --> Injected property
  }
}
like image 173
Ali Almoullim Avatar answered Nov 15 '22 07:11

Ali Almoullim


I think the best way to us a library in a vue 3 project is to use the depency injection https://v3.vuejs.org/guide/component-provide-inject.html

however I simply recommend that you import the library where you really need it, to have a more accurate intellisense, and a better three-shaking

like image 28
Cosimo Chellini Avatar answered Nov 15 '22 08:11

Cosimo Chellini