Using NPM Packages within Vue

As a Vue user you might have to frequently reach for standard javascript packages, since there isn’t always a Vue flavor, or if there is one it might be abandoned, or you don’t exactly want to mess with a middleman.

What do you do in that case? @Himanshu Sharma has a good writeup in SO.

First approach is on the app.js file (global)

window.x = require('package-name') 

The second approach is within the component (local)

<script>
import _ from 'lodash';

export default {
  created() {
   console.log(_.isEmpty() ? 'Lodash is available here!' : 'Uh oh..');
  }
} 
</script>

And Third method is using Vue.prototype within app.js or wherever you call Vue (global)

//app.js
import moment from 'moment';
Object.definePrototype(Vue.prototype, '$moment', { value: moment });

//within component
export default {
  created() {
    console.log('The time is ' . this.$moment().format("HH:mm"));
  }
} 

Leave a Comment