Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Yarn to Create an Alternative Import Name of an Installed Library


    In this lesson we'll show how to use yarn to alias the names of same npm libraries but install different versions. This could allow for easy migrating from one library version to an upgraded version.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    When using Yarn you have the ability to alias the npm name to something different and even install different versions of the same exact library from npm. Being able to install the exact library version is great, because it allows you to potentially migrate from one version of a library to the upgraded version of the library, as long as nothing conflicts in between them.

    If you don't have Yarn already installed or know what Yarn is, check out their website, yarnpkg.com, and you can see the install instructions for Mac OS, Windows, and Linux.

    Once we have Yarn installed, we will then type out the command here, so Yarn add. Yarn add is the equivalent of npm install.

    Now we'll type out the alias name that we want, so we will pick lodash 3. This is what you'd use when you import or require.

    Now we'll say @ and give it a target. We'll say the npm registry and the package lodash. This is the npm registry and this is the npm library that we want to alias as lodash3. However, this could be any library that you're referencing and this could be obviously any name.

    Now we'll give it a version so I'll say @ and then carrot3, which just says we want the third version, but it doesn't matter which one, so just give us the latest one. We'll install that.

    Now we'll install lodash 4, so we'll type Yarn add, and we'll alias it as lodash4. We'll say @npm lodash and then our version, so @ inaudible . This will install lodash as lodash 4, and we'll install the fourth version and the latest version of that.

    Now if we go take a look at our package.json, we can see that how it has been installed is just as we typed it -- lodash 3, lodash 4, and then the npm, which is the registry and the version of the library that we want.

    Now let's go show this actually working. We'll go to our index.js and we'll import lodash 3 from lodash 3 and import lodash 4 from lodash 4.

    We'll console.log lodash3.version and console.log lodash4.version. Save that and switch to our browser.

    If we refresh we can see that both versions are being console.logged, so the libraries are living on the same page at the same time.

    A word of warning, however -- this will only work if everybody on your development team and at your company and on your CI is using Yarn. If they use npm, this will not work.