While there are multiple ways to add JS -libraries to your VueJS project — proxying the library to a property of the Vue prototype object is the cleanest & most efficient way to do so.
• First lets add a library to your project:
npm install moment
• Then lets import that library and proxy it to Vue.prototype -object:
//main.js
import moment from 'moment';
Object.definePrototype(Vue.prototype, '$moment', { value: moment });
• Thats it — now you can use the library with:
export default {
mounted() {
console.log('The time is ' . this.$moment().format("HH:mm"));
}
}
Hope someone finds this useful ✌🏻
Top comments (4)
While you are absolutely right that proxying libraries will add weight to the global bundle I would still argue that these thing should be considered case by case. But as a warning I can join to your original comment 👍🏻 thanks!
Hi Matt! — So you saying that you shouldn't be using moment library ( what was a bad choice — i'll give you that ) or that you shouldn't proxy librarys at all and just import them component by component?
Hey, should this be Object.defineProperty instead?
Hi,
I'm relatively new to vue. I'd like to use the charts.js library in a vue component and was wondering if this approach would work?