DEV Community

loading...
Cover image for Apollo and Vuejs for Vitejs

Apollo and Vuejs for Vitejs

Leonid Rezvitsky
I love clean and beautiful code
・1 min read

Apollo and Vuejs for Vitejs

Background

Hey! For me, it was necessary to use apollo-client with Vite 2. And while there are no clean libraries that will work only with Vuejs, then we will manage with what we have. The Apollo team wrote a client only for react and therefore we have to mess things up from: @apollo/client/core

Start 🚀

First, we need to install the @apollo/client package. This can be done with the command below:

npm i @apollo/client // OR yarn add @apollo/client
Enter fullscreen mode Exit fullscreen mode

Then I started setting up the configuration to work with the backend.

// src/apollo/client.js

import { ApolloClient, HttpLink } from '@apollo/client/core'
import { InMemoryCache } from '@apollo/client/cache'

const httpLink = new HttpLink({
  uri: import.meta.env.VITE_API_URL
})

const apolloClient = new ApolloClient({
  link: httpLink, 
  cache: new InMemoryCache()
})

export default apolloClient
Enter fullscreen mode Exit fullscreen mode

We can now import apollo.js into the Vuejs component

// src/components/ApolloHello.vue

<script setup>
import apolloClient from '../apollo/client.js'
import { EXCHANGE_RATES } from '../graphql'

const { data: { rates } } = await apolloClient.query({
  query: EXCHANGE_RATES
})

console.log(rates)
</script>
Enter fullscreen mode Exit fullscreen mode

You also need to make changes to vite.config.js

{
    ...
    optimizeDeps: {
        include: [
            '@apollo/client/core',
            '@apollo/client/cache'
        ]
    },
    rollupInputOptions: {
        external: ['react']
    }
    ...
}
Enter fullscreen mode Exit fullscreen mode

What's next?

We can now use @apollo/client along with Vuejs. To try this stack, you can clone the repository

Discussion (2)

Collapse
ninjasoards profile image
David Y Soards

This is nice. Much simpler than any other setup I've found.

I did have to yarn add graphql to get it working though.

Collapse
rezvitsky profile image
Leonid Rezvitsky Author

At the moment there is vue-apollo (v4.apollo.vuejs.org/). It can be safely used in vitejs.