Install multiple major versions of a node module with npm

ยท 3 min read
Install multiple major versions of a node module with npm

In the last post of mine regarding React 17 upcoming release, we saw that React will let us use components trees managed by one major version inside a tree managed by a different one.

This means that we 'll end up having more than one major versions of React in our codebase, right?

So based on this I received this question from a couple developers:

How can I have more than one version of a module declared in package.json since it allows me to have only one?

The answer is that we can definitely declare many versions of the same module in package.json by using either npm either yarn.

# How can I declare them in package.json?

As of npm 6.9.0 we can use aliases to install modules across our applications. This pattern lets us declare N different versions in the package.json as long as we use a different alias for each version.

Only thing we have to do then is to call the correct alias in our code based on our needs.

As we see in the docs, the pattern we should use has this format:

npm install <alias>@npm:<name>@<version>

Let's give it a shot then:

npm install react17@npm:react@17
npm install react18@npm:react@18

The package.json will become like this:

"dependencies": {
  "react17": "npm:react@17",
  "react18": "npm:react@18"
}

So now in our component for React 17 we can do:

import React from 'react17';

// This will print 17.x.x
export default () => <>{React.version}</>;

while for React 18 we need:

import React from 'react18';

// This will print 18.x.x
export default () => <>{React.version}</>;

Don't get confused, React 18 isn't anywhere around yet while React 17 is in RC. These are mentioned here just for the shake of our examples.

We can achieve exactly the same result by using the aliasing mechanism of yarn as declared in the docs.

An example might be:

yarn add react17@npm:react@17
yarn add react18@npm:react@18

# Conclusion

So we definitely can declare multiple major versions of a module in our application's package.json as long as we use the aliasing mechanism offered by npm and yarn.

If you feel that all this is a bit messy - like I do - you can lazy-load your bundles that use different versions and keep things as clean and maintainable as possible.

Keep it simple and clean and remember that your future self will thank you when the time comes. Cheers!!

You can read the official docs if you need to go deeper regarding npm install

Did you like this one?

I hope you really did...

Marios_thumb

Newsletter

Get notified about latest posts and updates once a week!!