This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Add JavaScript Libraries from npm to Nuxt

    John LindquistJohn Lindquist

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss