Front-end core tools: how can yarn, npm and cnpm be used together gracefully?

  css, html, html5, javascript, node.js


The front-end of a poorly used package manager is an entry-level front-end and a poorly used front-end.webpackThe front end of is a primary front end

Three package managers can be used together, as long as you are bold and careful, there will be no problem!

InjaveScriptIn writing, we try not to define global variables and encapsulate functions as far as possible without side effects, because the query time of all variables will be slower than that of local variables, and we also consider the problem of not being garbage collected in the environment of Node.

The old rule is to look at the principle first.


  • npmYesNode.jsOne of the main reasons for such success.npmThe team has done a lot of work to ensure that npm remains backward compatible and consistent in different environments.
  • Npm is designed around the idea of semantic version control (semver).
  • Given a version number: major version number, minor version number and patch version number, the following three situations need to be added with corresponding version numbers:
  • Major Version Number: When API changes and is incompatible with previous versions
  • Subversion number: when the function is added but backward compatible
  • Patch Version Number: Used as a time to fix backward compatible defects
  • npm 2All dependencies that each package depends on are installed. If we have a project that depends on project a, project a depends on project b, and project b depends on project c, then the dependency tree will look like this:


  • This structure may be very long. This is only a minor annoyance for Unix-based operating systems, but it is a destructive thing for Windows because many programs cannot handle file pathnames with more than 260 characters.
  • npm 3A flat dependency tree was adopted to solve this problem, so our 3 project structures now look like the following:

Save the compressed package of each version that has been downloaded. The contents of the local cache can be viewed through the npm cache ls command. The design of local cache helps reduce installation time.

  • In this way, an original long file path name is changed from./node_modules/package-A/node_modules/package-B/node-modules/some-file-name-in-package-c.jsBecome/node_modules/some-file-name-in-package-c.js.
  • The disadvantage of this method is that,npmAll project dependencies must be traversed before deciding how to generate a flat node_modules directory structure. Npm must build a complete dependency tree for all used modules, which is a time-consuming operation and a very important reason for the slow installation of npm.
  • It is taken for granted that every runnpm installAt the time of the command,NPMAll content must be downloaded from the internet.
  • But,npmThere is a local cache, which holds the compressed package of each version that has been downloaded. The locally cached content can be accessed throughnpm cache lsCommand to view. The design of local cache helps reduce installation time.


  • cnpmwithnpmThe usage is exactly the same, except that when the command is executed, thenpminsteadcnpm.
  • npmThe installation plug-in was downloaded from a foreign server, which was greatly affected by the network, and there might be abnormalities. If npm’s server were in China, it would be good, so Taobao team did this. From the official website: “This is a completenpmjs.orgMirror image, you can use it instead of the official version (read-only), the synchronization frequency is currently 10 minutes to ensure synchronization with the official service as much as possible. “
  • Official address:
  • Installation:npm install -g cnpm --registry=


  • YarnThe main goal at the beginning is to solve the uncertainty of npm installation caused by semantic version control described in the previous section. Although it can be usednpm shrinkwrapTo implement a predictable dependency tree, but it is not the default option, but depends on all developers to know and enable this option.
  • YarnDifferent approaches have been taken. Each yarn installation generates a yarn.lock file similar to npm-shrinkwrap.json and is created by default. In addition to conventional information,yarn.lockThe file also contains checksums for the content to be installed to ensure that the libraries used are of the same version.
  • Yarn is a brand new npm client that has been redesigned. It enables developers to handle all necessary operations in parallel and adds some other improvements.
  • The operation speed has been significantly improved and the entire installation time has become less.
  • Like npm, yarn uses a local cache.Unlike npm, yarn can install locally cached dependencies without an Internet connection, which provides offline mode.
  • Permits to merge all packages used in the project
  • Installation through npm is generally not recommended. Npm installation is non-deterministic, the package is not signed, and npm does not perform any integrity check except for the basic SHA1 hash, which brings security risks to the installation of system programs. (The author once used it in a project that relied on hundreds of packages.)npmLost packets, the price is very big, tears unconsciously fell)

First of all, a very failed package download turned out to be a resource read from the global (not configuredwebpackThe alias is because this path is so long)


First of all, we start from the principle, we usenpm init,yarn init,cnpm initWhat happened at the time?

  • generatepackage.jsonFile
  • jsonThe file internally declares the initial version information, author information, etc. If you need to upload it to npm as a command line tool, you should configure it.binSuch as declaration entry fields

So when we usenpm i,yarn add,cnpm iWhat happens during the operation?

  • First, according to whether your command line suffix has been added-gOr ..globalJudging whether the downloaded package is placed in the global environment or currentpackage.jsonCorresponding to the filenode_moduleFolder directory (this is especially important, someone out of the BUG, because in usenpm,cnpmWhen did not indicate whether to add a global dependency or a local dependency, resulting injsonThere is no corresponding package name on the file, and the project will never get up).
  • Then according to your instructions--saveOr ..-D--save -devJudging whether it is development dependence or online dependence actually lies inyarnThere is no problem becauseyarnHas its own set of mechanisms to check the integrity of packets, will not lose packets, but also automatically determine the addition of dependencies, outbugGenerally speakingcnpmAndnpm, not clear-gOr ..--save,npmThere is only a mechanism to check the programmer’s signature, no mechanism to check the integrity of the package, and no automatic addition of dependencies to thejsonFile, then there will be the illusion of packet loss, so suggestMain useyarn



npmSummary of shortcomings of:

  • The same project cannot be installed consistently. Due to the characteristics of version numbers in package.json files, the following three version numbers represent different meanings during installation.
  • “5.0.3” means to install the specified version of 5.0.3, “~ 5.0.3” means to install the latest version in 5.0.x. “5.0.3” means to install the latest version in 5.X.X This is troublesome, often the same project will appear, some colleagues are OK, some colleagues will appear due to the different versions installed.bug.
  • At the time of installation, the package will be downloaded and installed at the same time. At some time in the middle, a package throws an error, but npm will continue to download and install the package. Because npm will output all logs to the terminal, there will be a lot of error information about the error package.npmThe printed warnings are lost and you will never even notice the actual errors.

yarnThe advantages of

  • Fast. The speed is mainly from the following two aspects:
  • Parallel installation: regardless ofnpmOr ..YarnDuring the installation of the package, a series of tasks are performed.npmEach is executed by queuepackage, that is to say, must wait until the currentpackageAfter the installation is completed, the subsequent installation can be continued. AndYarnAll tasks are executed in parallel, thus improving performance.

Offline mode:If a software package has been installed before, it will not need to be downloaded from the network like npm if it is retrieved from the cache when Yarn is installed again..

  • Unified installation version: to prevent pulling to different versions,YarnThere is a locked file(lock file)Record the version number of the module that is exactly installed. As long as one module is added at a time,YarnYarn.lock will be created (or updated). This ensures that each time the same project dependency is pulled, the same module version is used. Npm actually has a way to use the same version of packages everywhere, but it needs developers to execute it.npm shrinkwrapOrders. This command will generate a lock file that is executednpm installThe lock file will be read first, which is the same as Yarn reading yarn.lock file.npmAndYarnThe difference between the two is that,YarnBy default, such a lock file will be generated, and npm will pass throughshrinkwrapCommand generationnpm-shrinkwrap.jsonFile, only when this file exists,packagesVersion information will only be recorded and updated.
  • More concise output:npmThe output information of is rather lengthy. In progressnpm install <package>At the same time, the command line will continuously print out all the installed dependencies. In contrast, Yarn is too concise: by default, it combinesemojiDirectly and intuitively print the necessary information, and also provide some commands for developers to query additional installation information.
  • Multi-registration source processing: All dependent packages, no matter how many times they are indirectly referenced by different libraries, will only be installed from one registration source, either npm or bower, to prevent confusion and inconsistency.
  • Better Semanticization:yarnSome changes have taken place.npmThe name of the command, such asyarn add/remove,Feel better thannpmoriginalinstall/uninstallBe clearer.

Isn’t that the theme party? saidyarnWhy do we need so many advantages?npm?

You don’t have to.npm publishHow do you upload the package tonpm? You don’t have to.cnpm, can’t download some packages

Find out the essential results of downloading packages (dependencies) of the three:

  • First of all to the correspondingnode_moduleDownload the package under the folder (see you later if you have to go global)
  • Then there isjsonAdd a corresponding dependency field to the file to determine whether it is an online dependency or a development dependency.
  • As long as you do both, you will succeed
  • The conclusion is that as long as the result process cares what you are

UseyarnDownload the package and use it again.npm cnpmDownloads will be repeated and previous packages will be deleted.

  • puppeteerWhat this package depends onminiVersion of Google Browser UsedcnpmDownload can be the perfect solution
  • prerender-spa-pluginThis package depends on the abovePuppet puppet showThis bag can also be usedcnpmdownload
  • Mixed Use Package Manager Remember, Don’t Repeat Download Dependencies,npm cnpmDownload dependencies, must add indicate what dependencies, whether global installation
  • yarnAndnpm iThe reason for choosing the former is mentioned above. Generally speaking,yarnIs the best choice, but the other two are also indispensable, such aselectronThis dependency, usingcnpmIt can be perfectly installed with one click.

As long as you are bold and careful, you can use them like a duck to water. Otherwise, you will be rubbed on the ground. It is normal for you to step on the pit during the practice process. Don’t forget to pay attention to my column and praise it before you go ~