I haven’t written an article for a long time. The reason for writing this article is an interview question I met last week. Please implement an NPM install

Write a short article to briefly explore its build process

After NPM install is executed, it goes to package.json to find Dependencies. Use this “map” to write all dependencies for this project to node_modules.

File download and write of course not difficult, here the core is the dependency tree creation, right

Let’s start with a simple dependency

But what if 2 also depends on 4?

This was first done in previous NPM releases

This is clear, but if the dependency tree is large and there are many of the cases described above. Both memory and requests are wasteful

So after NPM3, the strategy changed. Pat the tree as flat as you can. What does that mean?

It will first place the node at the top of the tree as it iterates through the dependencies. That is, for example, the four dependencies in the figure above hang to the first layer and do not build a subtree. At this time, another dependency 4 node is added. So the first thing you’re going to do is determine if it’s already in the first layer, and if it’s already there, you don’t have to deal with it.

If you iterate through the build first

What if they add a version?

For example, if 1 depends on 4.1 and 2 depends on 4.2, how can we build it?

At this point, a hybrid build of NPM 2+ NPM 3 will be used. That is, 4.1 was already in the first layer when 4.2 was built. The 4.2 will still be attached to its original father

Originally depends on the tree

Build the dependency tree

This may seem like a solution to the pre-NPM2 problem, but when building dependencies. The order in which you start building depends on the order in which you write in Dependencies.

What could possibly go wrong? Here’s another chestnut

Suppose the original dependency is like this

Once you’ve built it

At this point, there seems to be no problem. What if we change the order in dependencies? Such as this

Once the build is complete

It can be seen that the repetition problem in the fundamental construction has not been solved

What to do? NPM in 5.x also generates the lock file (package-lock.json) for locking dependencies. That’s out of my article

Reference: myan. Im / 2018/03/24 /…