Vue build didnt include my function to output .js file

Viewed 98

Works fine in dev mode, but after build process vue not includes setupToken function (from @/api.js) to app.js output file.

// App.vue
//...
import { setupToken } from '@/api
export default {
  mounted () {
    this.setupToken() // TypeError: this.setupToken is not a function
  }
}

// @/api.js
import { mande } from 'mande'

export const postsAPI = mande(`${process.env.VUE_APP_ROOT_URL}/api/v1/posts`)

export const setupToken = ({ token }) => {
  postsAPI.options.headers.Authorization = 'Bearer ' + token
}

I guess the problem with webpack config (im using default one), but not sure how to fix it.

2 Answers

setupToken does not exist on the object you're exporting from App.vue.

You are importing setupToken from @/api so you have to call it directly, i.e. setupToken() and not as an instance method, i.e. this.setupToken()

WebPack sees you are not using the method you're importing from @/api (because you are calling it as an instance method) so it tree-shakes it out.

BTW, try using TypeScript, it would have let you know of that error.

  1. Import api.js in main.js
    import Vue from 'vue'
    import App from './App.vue'
    import api from './api'
    
    Vue.config.productionTip = false
    
    new Vue({
      api,
      render: function (h) {
        return h(App)
      },
    }).$mount('#app')
  1. Modify api.js:
   import Vue from 'vue'  
   Vue.mixin({
      methods: {
        setupToken({ token }) {
          postsAPI.options.headers.Authorization = 'Bearer ' + token
        }
      }
    }
Related