2

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.

0

2 Answers 2

4
+300

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.

0
1
  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
        }
      }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.