⚠️ This lesson is retired and might contain outdated information.

Add JavaScript Libraries from npm to Nuxt

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 months ago

You can install libraries from npm as usual, but you need to be aware of the vendor property of your nuxt.config.js so that the library only gets loaded once with your application. This lesson walks you through the appropriate steps of adding axios to your project and setting it up as a vendor library in your nuxt.config.js.

To add a third party library, just go ahead and npm install it. I'm going to use Axios as my example.

Then we can update our config, so I'll add back the build property, and our build vendor will include Axios. This line simply means we want to add Axios to the vendor bundle so that it only gets included once rather than every time it's imported.

Then we're going to add a file to plugins. We'll call this axios.js, and I'll say import Axios from Axios, and then export default Axios. I'm just going to use the GitHub API as the base URL, so I'll add that in here. Anywhere I access Axios, it'll have the GitHub API prepended to it.

I can import it here, import Axios from that same ~/plugins/axios, and then in the object that we export from our script, I can use the async data method to return a promise, so we'll return axios.getusers.

Again, that's the GitHub API and /users, then take the response and return an object that has users assigned to the response.data. I'll run a server again, and then make some visual changes to show this is working. If I just add in users here, you'll see an array with a bunch of data in it.

Since that's an array, I can go ahead and do a V4 on this, so V4 user in users. We also need the key on there, and the key can be the user ID.

Inside of our list element, we can say user.login, and when I go ahead and save that, we'll now have all that data, all of the logins from the GitHub API show up in my list.

Victor Hazbun
Victor Hazbun
~ 6 years ago

You should explain the asyncData function, not everybody here understands why it worked even when you did not called the function directly, here is the docs if someone else feels confused about it: https://nuxtjs.org/api/

Markdown supported.
Become a member to join the discussionEnroll Today