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.)
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';
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.
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.
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.
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
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With