DEV Community

mmmrks
mmmrks

Posted on

Using any JS library with VueJS

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
Enter fullscreen mode Exit fullscreen mode

• 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 });
Enter fullscreen mode Exit fullscreen mode

• Thats it — now you can use the library with:

export default {
 mounted() {
  console.log('The time is ' . this.$moment().format("HH:mm"));
 }
}
Enter fullscreen mode Exit fullscreen mode


Hope someone finds this useful ✌🏻

Top comments (4)

Collapse
 
mmmrks profile image
mmmrks

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?

 
mmmrks profile image
mmmrks • Edited

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!

Collapse
 
martynwheeler profile image
martynwheeler

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?

Collapse
 
totaldog profile image
totaldog

Hey, should this be Object.defineProperty instead?