how use npm packages with Vue SPA
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 ?
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');