[Vuejs]-How to import javascript library in main.js for global availability throughout vue app?

1👍

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

2👍

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

Leave a comment