Vincenzo Raco
My Developing Blog

My Developing Blog

How to Set Up Axios in a VueJS Typescript Project

Vincenzo Raco's photo
Vincenzo Raco
·Jun 16, 2019·

min read

Today, I am going to show you how to set up axios in your typescript VueJS project.

First of all, we install the package though npm:

npm install axios

We then create our axios.ts file. I believe that saving the file in the plugins folder makes our project structure cleaner, but feel free to save it wherever you prefer.

Inside our axios.ts file, we write the following code:

import Vue from 'vue';
import axios, {AxiosStatic} from 'axios';

Vue.use({
    install() {
        Vue.prototype.axios = axios.create({
            baseURL: process.env.VUE_APP_API_URL,
        });
    },
});

declare module 'vue/types/vue' {
    interface Vue {
        axios: AxiosStatic;
    }
}

We will then be able to use this.axios everywhere in our project, and our IDE will know its methods, as we declare the axios interface at the bottom of the file.

And one more thing, don't forget to import the file :)

That's all to it.

If you have any questions, please leave a comment below.

 
Share this