Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

Time:2019-10-23

Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

A front end that doesn’t work well with package managers is an entry-level front end that doesn’t work wellwebpackThe front end is a primary front end

Three package managers can be used together, as long as you are bold enough, no problem!

  • Recommend two articles

    • Handwritten React scaffolding
    • Handwritten Vue scaffolding
    • Front-end performance optimization incomplete manual

injaveScriptIn writing, we try not to define global variables and encapsulate functions without any side effects, because the query time of all variables will be slower than that of local variables, especially considering the problem that they cannot be garbage collected in Node environment

Old rules first look at the principle

npm

  • npmis Node.jsOne of the main reasons for this success.npmThe team did a lot to ensure that NPM remained backward compatible and consistent across different environments.
  • NPM is designed around the idea of semantic versioning (semver).
  • Given a version number: major version number, minor version number, patch version number, the following three situations need to increase the corresponding version number:
  • Major version number: when the API changes and is incompatible with previous versions
  • Minor version number: when functionality is added, but backwards compatible
  • Patch version number: when a backward-compatible bug is fixed
  • 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, the dependency tree would look like this:

Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

  • This structure can be very long. This is no more than a minor annoyance for unix-based operating systems, but it can be devastating for Windows, as there are many programs that can’t handle more than 260 characters of file pathnames.
  • npm 3A flat dependency tree was adopted to solve this problem, so our three project structures now look like this:

Saved each version of the archive that you downloaded. The contents of the local cache can be viewed through the NPM cache ls command. The design of the local cache helps reduce installation time.
Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

  • In this way, an originally very long file path name from./node_modules/package-A/node_modules/package-B/node-modules/some-file-name-in-package-c.jsTurned out to be/node_modules/some-file-name-in-package-c.js
  • The downside of this approach is that,npmYou must first walk through all the project dependencies before deciding how to generate a flat node_modules directory structure. NPM must build a complete dependency tree for all the modules it USES, which is a time-consuming operation and an important reason for the slow installation of NPM.
  • Take it for granted that every runnpm installCommand,NPMYou have to download everything from the Internet.
  • However,npmThere is a local cache that holds every version of the archive that has been downloaded. The contents of the local cache can be passednpm cache lsCommand to view. The design of the local cache helps reduce installation time.

cnpm

  • cnpmwithnpmThe usage is exactly the same except when executing commandsnpmInstead ofcnpm
  • npmInstallation plug-in downloaded from foreign servers, affected by the network, may appear abnormal, if the NPM server in China is good, so taobao team did this. From the official website: “this is a completenpmjs.org Mirror, you can use this instead of the official version (read only), sync frequency is currently 10 minutes to ensure as much sync as possible with the official service.
  • Official address:http://npm.taobao.org
  • Installation: npm install -g cnpm --registry=https://registry.npm.taobao.org

Yarn

  • YarnThe primary goal in the beginning was to address the uncertainty of the NPM installation due to semantic versioning described in the previous section. Although you can usenpm shrinkwrapTo implement a predictable dependency tree, but it is not the default option, it is up to all developers to know and enable this option.
  • YarnA different approach was taken. Each yarn installation generates a yarns.lock file similar to npm-shrinkwrap. Json, and it is created by default. In addition to the general information,yarn.lockThe file also contains a checksum of what is to be installed to ensure that the version of the library used is the same.
  • Yarn is a new NPM client that has been redesigned to allow developers to do all the necessary work in parallel and add some other improvements.
  • The running speed was significantly improved and the overall installation time was reduced
  • Like NPM, yarn USES local caching.Unlike NPM, yarn installs local cache dependencies without an Internet connection and provides an offline mode
  • Licenses that allow you to merge all packages used in your project
  • Installation via NPM is generally not recommended. NPM installation is non-deterministic, packages are not signed, and NPM does not perform any integrity checks other than basic SHA1 hashing, which poses a security risk to installing system programs. The author used it in a project that relied on hundreds of packagesnpmI lost my bag, which cost me a lot. My tears fell down unconsciously.

First look at a very failed package download that actually reads resources from the global (not configuredwebpackIt’s called because it’s this long.)

Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

First we start with the principle, and we use npm init, yarn init ,cnpm initWhat happened?

  • generatepackage.jsonfile
  • jsonFile internal declaration of the original version information, author information, etc., if you need to be uploaded to NPM as a command line tool, should be configuredbinDeclare the entry field

So when we usenpm i , yarn add ,cnpm i What happens when you do that?

  • First, it will depend on whether your command line suffix is added-g orglobalDetermine whether the downloaded package is in the global environment or the current onepackage.jsonFile correspondingnode_moduleFolder directory (this is especially important, someone out of the BUG, just because in usenpm , cnpmThe result of not specifying whether the added dependency is global or localjsonThere is no corresponding package name on the file, and the project will never get up.)
  • Then follow your instructions--save or-D--save -devDeciding whether it is a development dependency or an online dependency is, in fact, the pointyarnNo problem with that, becauseyarnHas its own set of check package integrity mechanism, will not lose the package, will also automatically determine the addition of dependencies, outbugThe general iscnpmandnpmIt’s not clear-gor--savenpmThere is only a mechanism to check programmer signatures, there is no mechanism to check package integrity, and dependencies are not automatically added tojsonFile, then it will appear the illusion of lost package, so suggestThe main use ofyarn

yarnandnpmcontrast

Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

npmSummary of disadvantages:

  • Same project, installation time cannot maintain consistency. Due to the nature of the version number in the package.json file, the following three version Numbers represent different meanings when installed.
    "5.0.3",
    "~5.0.3",
    "^5.0.3"
  • “5.0.3” means install the specified version 5.0.3, “~ 5.0.3” means install the latest version 5.0.x, and “^5.0.3” means install the latest version 5.0.x. This is a problem, often the same project, some colleagues are OK, some colleagues will be due to the installation version is not consistentbug
  • During installation, packages are downloaded and installed at the same time. At some point, one package throws an error, but NPM continues to download and install packages. Because the NPM outputs all the logs to the terminal, the error messages about the error packages will pile upnpmThe printed warning is missing, and you’ll never even notice the actual error.

yarnThe advantages of

  • Speed is fast. The fast speed mainly comes from the following two aspects:
  • Parallel installation: regardlessnpmor Yarn When you perform the package installation, you perform a series of tasks.npm Each is executed on a queue package“, which means it has to wait until now package After the installation is complete, the subsequent installation can proceed. whileYarnParallel execution of all tasks improves performance.

Offline mode:If you have previously installed a package and retrieved it from the cache at Yarn reinstallation, you do not need to download it from the network as NPM does

  • Installation version unification: to prevent pulling different versions,YarnThere is a lock file(lock file) Records the version number of the module being installed exactly. Every time a new module is added,YarnYarns. lock is created (or updated). This ensures that the same version of the module is used each time the same project dependency is pulled. NPM does have a way to implement packages that use the same version everywhere, but requires the developer to executenpm shrinkwrap Command. This command will generate a lock file during executionnpm install , the lock file will be read first, just as Yarn reads the yarn.lock file.npmandYarnThe difference between the two is that,YarnBy default, such a lock file is generated and the NPM passesshrinkwrapCommand to generatenpm-shrinkwrap.jsonFile, only if this file exists,packagesVersion information is recorded and updated.
  • Cleaner output:npm The output is verbose. In the implementation npm install <package>The command line will print out all installed dependencies. Yarn, by contrast, is too terse: by default, it combines emojiPrint out the necessary information visually and directly, and provide commands for developers to query for additional installation information.
  • Multi-registration source handling: all dependent packages, no matter how many times they are referenced indirectly by different libraries, will be installed from only one registration source, either NPM or bower, to prevent confusion and inconsistency.
  • Better semantics:yarnChanged a little bitnpmThe name of the command, for exampleyarn add/remove,In the sense than npm The originalinstall/uninstallBe clear.

That’s not headline party? Said theyarnWith all these advantages, why do we need themnpm?

You don’t have tonpm publish, how do you upload package tonpm? You don’t have tocnpmYou can’t download some packages

Figure out the essential results of the three download packages (dependencies) :

  • First to the correspondingnode_moduleDownload the package under the folder (if you must go to the whole thing, then goodbye)
  • thenjsonAdd the corresponding dependency field in the file to determine whether it is an online or a development dependency
  • Do both and you’ll be successful
  • The bottom line is as long as the outcome process doesn’t matter what you are

useyarnDownload the package and use it againnpm cnpmThe download will repeat the download and delete the previous package

  • puppeteerThis package depends onminiGoogle version of the browser to usecnpmDownload is the perfect solution
  • prerender-spa-pluginThis package depends on the abovePuppet show puppeteerThis bag can also be usedcnpmdownload
  • Mix package managers remember, do not repeat download dependencies,npm cnpmDownload the dependencies, be sure to add what the dependencies are, global installation
  • yarnandnpm iThe reasons for choosing the former are mentioned above. In general,yarnIs the only choice, but the other two are also indispensable, such aselectronThis dependency is usedcnpmCan be a perfect one button installation

As long as bold and careful, you can use the three like a fish in water, otherwise it will be pressed on the ground friction, practice process is normal to feel good writing don’t forget to pay attention to my column, give a like to go ~