I've been trying to add Axios to the Vue prototype so I can access it as this.$http. I'm using Typescript so I need the type definitions for this too. I've seen plenty of places on the internet that describe how to do this, but no matter what I try, Typescript doesn't recognise my definitions and I get the error:
Property '$http' does not exist on type
I think it's something to do with my tsconfig.json, but I'm not sure. Please see below the relevant files:
src/plugins/axios.ts
import _Vue from 'vue';
import Axios from 'axios';
export function AxiosPlugin<AxiosPlugOptions>(
Vue: typeof _Vue,
options?: AxiosPluginOptions,
): void {
Vue.prototype.$http = Axios.create({
baseURL: options?.baseUrl,
});
}
export class AxiosPluginOptions {
baseUrl = '';
}
src/types/axios-plugin.d.ts
import { AxiosStatic } from 'axios';
declare module 'vue/types/vue' {
export interface Vue {
$http: AxiosStatic;
}
}
src/main.ts
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import vuetify from './plugins/vuetify';
import { AxiosPlugin } from './plugins/axios';
Vue.config.productionTip = false;
Vue.use(AxiosPlugin, {
baseUrl: 'https://localhost:44390/api/',
});
new Vue({
router,
store,
vuetify,
render: (h) => h(App),
}).$mount('#app');
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"typeRoots": [
"./node_modules/@types",
"./node_modules/vuetify/types",
],
"types": [
"webpack-env",
"vuetify"
],
"paths": {
"@/*": [
"src/*",
],
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
Does anyone know why my type declaration is not being recognised?
src/**/*.d.tsto your include list in tsconfig.ts?