how use npm packages with Vue SPA

Zaid Direya picture Zaid Direya · Jan 29, 2017 · Viewed 11.2k times · Source

i have created Vuejs app using vue-loader,now i need to use an installed npm package as follow :

but i have this error :

Uncaught TypeError: plugin.apply is not a function

dose Vuejs require a special type packages or it can work with any JavaScript package and this error can be solved

Answer

Himanshu sharma picture Himanshu sharma · Jan 31, 2018

There are many approaches.

I am adding with respect @smiller comment and thanks for sharing the link . I am adding information here in case the link someday not work .

Credit to this link :- https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

First approach of-course @crig_h

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

There are certain drawback . don’t work with server rendering . Otherwise everything will work fine in browser as window is global to browser , any properties attract to it will be accessible to whole app.

The second approach is .

Use Import with the js portion in the .vue file , Like this.

if inside the '.vue' file.

<script>
import _ from 'lodash';

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

If you have seperate file for .js then same like this there will we no <script> tag.

And Third method

where ever in the project you import vue. You can write this statement import Vue from "vue";

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

This will set the relevant properties to to Vue . And you can use it any where like this . As Vue is global scope of app.

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

ADDED FOR CSS

you can do import in src/main.js file in vue.js project .

import './animate.css'

Also if you like to import in template .

Inside the template you can do this.

<style src="./animate.css"></style>

Also have a look on css-loader package . what it does ?