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.
CodePudding user response:
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.
CodePudding user response:
Import
api.js
inmain.js
Modify
api.js
:Vue.mixin({ methods: { setupToken({ token }) { postsAPI.options.headers.Authorization = 'Bearer ' token } }