Code sharing scheme

This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Early on we needed to share our code, and our first choice was Github

That is, we upload it to GitHub, where other programmers download our code and manually reference it

  • Users need to know the corresponding Github address, and need to manually download and import
  • The dependencies of corresponding packages need to be manually maintained
  • You need to manually remove dependencies when they are not needed
  • Repeat the above steps when you have a version update or a bug fix

As projects get larger, the number of libraries a project needs to rely on grows

And library dependencies and dependencies between libraries are becoming more cumbersome

This traditional way of updating and managing libraries is cumbersome and error-prone

So we need a tool to replace this complex and error-prone manual management

And that tool is the Package Management Tool (NPM)

We use tools to publish code to specific locations, and other programmers directly use tools to install, upgrade, and remove our tool code

npm

Node Package Manager is the Node Package Manager

But it’s not just the Node package manager anymore, it’s also used in front-end projects to manage dependent packages

Detection address and warehouse address

We can search for packages (third-party libraries) we need to use at www.npmjs.com/

However, this library only plays a lookup function, we actually publish and download the corresponding package to the REGISTRY corresponding to the NPM

The configuration file

In fact, we have a configuration file for each project, whether it is a front-end project (Vue, React) or a back-end project (Node).

This configuration file will record your project name, version number, project description, and so on

It also keeps track of other libraries that your project depends on and the version numbers of those libraries

This configuration file is package.json

#Generate the configuration file package.json
$ npm init

#Quick configuration file generation - use all default values
#If you need to quickly generate the corresponding configuration file, the package name must be legitimate - all lowercase, multiple words are separated by a hyphen
$ npm init --yes | -y
Copy the code
Common properties
The property name function note
name Project name mandatory
version The version number of the project 1. Required

2. Follow the Semver specification
description Basic description of the project The default value is an empty string
author Author Information This property has no effect on private projects, which are needed when publishing
license Open source licenses 1. Default ISC

2. This property does not work for private projects
keywords Keywords corresponding to the project The query keyword corresponding to the item search
private Whether the project is open source 1. Value is a Boolean value

2. If the value is true, then NPM cannot publish it, which is a way of preventing private projects or modules from being published
main The main entry file for the project 1. The default is index.js

2. This property is used only when the project is published. If the project is locally private, this property does not take effect

3. If the project is open source, for example, an open source third-party package, the index.js file in the root directory of the project will be searched by default when the dependency graph is built after the package is imported. If the main entry file of the project is not index.js in the root directory, the specified file will be displayed in the main field
scripts Used to configure script commands in the form of key-value pairs 1. After the configuration, you can run the script using the key of the NPM run command

2. Run NPM run < script key value (script name) >

3. You can run the start, test, stop, and restart commands directly by using NPM start
dependencies Both development and build environments require dependent packages 1. If you run the NPM install command, the library in the Dependencies field is downloaded

2. If you install NPM install, the dependencies field of the library will be downloaded as well
devDependencies Packages that are needed at development time
peerDependencies Peer dependencies that use this package in the project 1. The packages described in the peerDependencies field must exist in the corresponding project before the peerDependencies field is installed

2. If the peerDependencies do not exist, the library can be downloaded normally, but a warning is displayed indicating that the user needs to download the corresponding package in peerDependencies

3. For example, when downloading the library of Element-Plus, it will prompt the user that the library is dependent on VUe3. If the user directly downloads The library of Element-Plus without downloading the vue3 package, there will be a warning message. Vue3 is the peerDependencies of Element-Plus.
engines The Engines property is used to specify the version numbers of Node and NPM 1. During the installation, the system checks the corresponding engine version first. If the version does not match, an error message is displayed

2. Rarely
homepage The corresponding official website address of the project 1. Use it for release

2. If there is an official website, fill in the official website address. If there is no official website, fill in the Github address
repository Project Warehouse Address 1. The value type is an object

2. The value of the type attribute is used to set the repository type to git

3. The value of the property URL is used to set the address of the warehouse
Some other properties Browserslist, eslintConfig, etc Package. json is actually a JSON file, so some third-party configuration tools will also configure their corresponding configuration information into package.json, and they will read package.json during parsing

Common instruction

#Check the version
$ npm --version | -v

#Ps: the I in the following command is short for install. You can use either install or I

#Download all dependencies
$ npm i

#Download third-party packages - packages needed by both development and production environments (mainly libraries that will be used in projects)
$ npm i <package> [--save]

#Download third-party packages that are required for use by the development environment
$ npm i <package> -D | --save-dev

#Install a specific version of the package
#If you need to install the latest version of the package - write the value of version as latest
$ npm i <package>@<version>

#Global installation library - used as a tool library, especially if you need to use it from the command line
#Sometimes, we need both a global and a local installation for a particular tool library (e.g. Webpack)

#The global installation is designed to make these libraries available on the command line
#A partial installation allows for the use of multiple versions of the libraries across multiple projects, while keeping the versions of the libraries consistent across the project team
$ npm i <package> -g

#Uninstall the corresponding package
$ npm uninstall | un <package> [-g]
Copy the code

Although in the actual release process, our project will be packaged by a compilation tool before being released

When the compiler packages, it builds the dependency graph from the entry file,

If a library does not exist on the dependency diagram, the corresponding library is not packaged into the final project file

So even if we add all of our development-time dependencies to the Dependencies field, we remove them from the project during the actual packaging process

However, we recommend adding development-time dependencies separately to the devDependencies field in order to be as compliant as possible with the corresponding specification

Not all of them in the Dependencies field

semver

NPM packages are usually versioned in accordance with the Semver versioning specification

Semver (Semanic Version) is the semantic version specification

#Major version. Minor version. Revised version number
# major.minor.patch
Copy the code
field describe
major 1. The API changes of previous versions are not compatible

2. The architecture of the project was iterated and upgraded as a whole
minor Backward compatible functionality additions – New functionality is added, but compatible with previous versions
patch Backward compatibility fixes – no new features, bug fixes from previous versions
The descriptor function note
^ Lock the main version ^ X.Y.Z: indicates that x is constant, y and z are always installed with the latest version
~ Lock major and minor versions ~ X.Y.Z: indicates that x and y remain unchanged, and Z always installs the latest version

Principles of NPM install

  1. Check for package-lock.json

    1.1 there is no

    • Start from the entry file to build the corresponding dependency diagram
    • To the correspondingregistryWarehouse for search, and download the corresponding compression package
    • Add the corresponding compressed package to the cache (the cache actually consists of two parts – the compressed package + the configuration file describing the compressed package)
    • Decompress the required package and place it in thenode_modulesIn the
    • generatepackage-lock.json(package.jsonThe version in is a scope version, not a concrete version, andpackage-lock.jsonThe installed version is the actual version used.

    1.2 there are

    • Detects dependency consistency (that is, whether the versions in the cache matchpackage.jsonThe corresponding scope version of
    • If inconsistent, rebuild the dependency, and if consistent, look up the corresponding cache
    • If the cache is not looked up, go to the correspondingregistryDownload the corresponding library, find the decompression package placed tonode_modulesIn the

package-lock.json

{
  "name": "js-advance"./ / project name
  "version": "1.0.0".// Project version
  "lockfileVersion": 2.// package-lock.json is the generation of the file
  "requires": true.// Requires is used to track module dependencies, which requires requires to add dependencies to the requires field. The flattening of configuration information is easy to maintain and search for, and helps prevent multiple downloads of the same library version
  "packages": {
    "": {
      "name": "js-advance"."version": "1.0.0"."license": "ISC"."dependencies": {
        "axios": "^ 0.24.0"}},"node_modules/axios": {
      "version": "0.24.0"."resolved": "https://registry.npmmirror.com/axios/download/axios-0.24.0.tgz"."integrity": "sha1-gE5voeS5xSiFAd2d/1anoJQNINY="."license": "MIT"."dependencies": {
        "follow-redirects": "^ 1.14.4"}},"node_modules/follow-redirects": {
      "version": "1.14.5"."resolved": "https://registry.npmmirror.com/follow-redirects/download/follow-redirects-1.14.5.tgz"."integrity": "sha1-8JpYSJgdPHcrU5Iwl3hSP42Fw4E="."funding": [{"type": "individual"."url": "https://github.com/sponsors/RubenVerborgh"}]."license": "MIT"."engines": {
        "node": "> = 4.0"
      },
      "peerDependenciesMeta": {
        "debug": {
          "optional": true}}}},"dependencies": {
    "axios": {
      "version": "0.24.0".// The version used for the actual installation
      "resolved": "https://registry.npmmirror.com/axios/download/axios-0.24.0.tgz".// The package corresponds to the warehouse
      "integrity": "sha1-gE5voeS5xSiFAd2d/1anoJQNINY=".// The sha1 key will be decrypted during the actual operation, and finally get the index value. Through this index value, we can go to the cache to find the corresponding configuration file. Through the configuration file, we can find the package we need to use in the cache
      "requires": {
        "follow-redirects": "^ 1.14.4" // The third-party library that the AXIos library depends on}},"follow-redirects": {
      "version": "1.14.5"."resolved": "https://registry.npmmirror.com/follow-redirects/download/follow-redirects-1.14.5.tgz"."integrity": "sha1-8JpYSJgdPHcrU5Iwl3hSP42Fw4E="}}}Copy the code
#NPM views the cache address
$ npm config get cache

#Clear the cache
$ npm cache clean [-f]

#View the NPM image
npm config get registry

#Set up an NPM image
npm config set registry https://registry.npm.taobao.org
Copy the code

yarn

Yarn is a new JS package management tool created by Facebook, Google, Exponent and Tilde

Early NPM had many drawbacks, such as slow installation dependency, version dependency confusion and a series of problems

So yarn was originally created to compensate for some of the shortcomings of NPM

Although many upgrades and improvements have been made since NPM5, many people still prefer to use YARN

The version management file of YARN is yarn.lock, although the main configuration content is basically the same as package-lock.json

But yarn.lock is not a configuration file, but a special format file

Therefore, it is not recommended to use YARN and NPM together. Version management exceptions may occur

npx

NPX is a command that comes with NPM5.2

NPX has many uses, but it is common to use it to invoke instructions from a module in a project

Let’s take webPack as an example

Suppose we have [email protected] in the project and the global presence [email protected]

#If we look at the webpack command directly from the command line
#The local webpack is installed in node_modules/.bin
#So the global Webpack is found and used
$ webpack --version # v5.46.0
Copy the code

There are two common ways to use a project’s (partial) Webpack:

  1. Explicitly look for webpack under node_module
$ ./node_modules/.bin/webpack --version # 3.6.0
Copy the code
  1. Define a script in scripts to execute the Webpack

By default, scripts defined in scripts will be searched in node_modules/. Bin. If it is found, it will be used directly; if it is not found, it will be searched globally

"scripts": {
  "webpack": "webpack --version"
}
Copy the code
  1. The use of NPX

NPX will go to node_modules/. Bin to find the corresponding package and use it if it finds it, use it if it doesn’t find it globally, use it if it doesn’t find it globally, download it to a temporary folder if it still can’t find it globally, and use the corresponding package. Wait until the corresponding package is used. The corresponding temporary files are automatically removed.

So if we want to use a package on the command line but don’t want to install it globally, we can use NPX, temporarily use the package, and remove the package when we’re done

$ npx webpack --version # 3.6.0
Copy the code

Publish your own package

  1. Register an NPM account
  2. usenpm loginCommand to log in to your NPM account
  3. usenpm publishCommand to publish your own library (if it has been published and needs to be republished, update the version number before publishing)
  4. usenpm unpublishCommand to delete libraries that you have already published
  5. usenpm deprecateCommand to make published libraries expire (when searching for them using NPM, a message indicating that the libraries have expired is displayed)