Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use npm packages with Vue SPA

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

   var x = require('package-name')
   Vue.use(x)

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

like image 320
Zaid Direya Avatar asked Jan 29 '17 13:01

Zaid Direya


2 Answers

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 ?

like image 159
Himanshu sharma Avatar answered Sep 28 '22 12:09

Himanshu sharma


Plugins are specific Vue packages that add global-level functionality to Vue, so if you aren't using a Vue plugin then you don't need to register it with Vue using Vue.use().

In general there isn't any issue using non-view specific packages via npm but if you need to register something globally, you can usually get away with simply attaching it to window like so:

window.x = require('package-name');
like image 21
craig_h Avatar answered Sep 28 '22 12:09

craig_h