Home > Software design >  How to import javascript library in main.js for global availability throughout vue app?
How to import javascript library in main.js for global availability throughout vue app?

Time:10-28

My main.js contains import "mathjs"; and seems to be working fine within main.js as

console.log(median(5,4,6,1));
> 4.5

median() is however not available outside of main.js, i.e. in components. After reading this answer, I assumed that the simple import should be enough for global availability throughout the vue app?

CodePudding user response:

in main.js import all as math then add it as global property :

import * as math from 'mathjs'


const app=createApp({....})

app.config.globalProperties.$math =math

then in any component you could use it like this.$math.theFunctionName

CodePudding user response:

In general when you are working with modern modules or a bundler like webpack, you have to import mathjs in every module (think file) you want to use it.

What is often done in the vue context, is adding the library to the Vue context itself with a plugin.

See https://v3.vuejs.org/guide/plugins.html#writing-a-plugin

So this should be as easy as:

const mathjsPlugin = {
  install(app){
    app.config.globalProperties.$mathjs = mathjs;
  }
}

const app = createApp(...);

app.use(mathjsPlugin);

// inside of a component
export default {
  created(){
    console.log(this.$mathjs....);
  }
}

I personally think explicitly importing is a cleaner approach, but if mathjs is used in most of the components, this approach can make sense

  • Related