preface

Briefly summarize the reasons for writing this article:

I wrote this article because some time ago someone asked me whether she knew the version of the problem in package.json during the interview. What do the ~, >, ^, etc. for installing modules stand for? She told me, usually just use the project in the NPM start or build the project, really no one to understand so much, when the mentality collapsed O (╥﹏╥)oo(╥﹏╥) O, behind the interview also failed to answer.

I give advice is, in the interview or difficulties at ordinary times it is very normal, the front-end problems many are trying very hard, is a process of growth, this time we have to say the truth, say there is no specific understanding, back after I go a lot this knowledge, or to ask the interviewer, is possible, also won’t because of this problem, you will pass. The interviewer will investigate this convenient question, on the one hand is based on their own business encountered these problems, and is to investigate the interviewer to master the front-end foundation and depth and breadth, we really do not know, convey to the interviewer we have the spirit of learning exploration.

Objective: What can you learn from this article?

  • 1. About NPM
  • 2. What is package.json?
  • 3, how to create package.json
  • 4. What is the difference between global and local installation?
  • 5. Install, update and uninstall modules
  • 6. Version of the module in package.json^ 2.0.0 ` ` ~ 2.0.0Etc. (used by the installed version@What does it mean?NPM install [email protected])
  • 7. Detailed description of each field in package.json
  • 8. Version numberversionMeaning, for example, big updates, adding some features to the launch, fixing some little puddings to the launch, how do we change the package version number? How does it work with Git
  • 9, release number cycle, phase, (-alpha, -beta, -rc are what phase of the cycle project, which are the developers packaged projects, which are the testers of the project, the project online)
  • Some other NPM commands
  • 11. Understand the direct relationship between package.json and your project
  • 12. How to find modules when require introduce modules

Json. What is NPM? How do you install it?

npm

NPM is a widely used package management tool for front-end development that opens up the entire JavaScript world to you and your team. Open source developers from all continents use NPM to share and borrow packages, and many organizations use NPM to manage proprietary development.

1. What is NPM?

Official introduction:

npm makes it easy for JavaScript developers to share and reuse code, and it makes it easy to update the code that you’re sharing.

Ps: the official website www.npmjs.com/ browse, search, download and install the modules uploaded by others you want, you can also directly search in the command line.

In our program development, we often need to rely on frameworks provided by others. We can see that some large VUE and React frameworks also have modules or packages that rely on others, which can improve efficiency and avoid duplication of wheels. In addition, these wheels often have better user experience. A package or module will have a package.json file that describes the package.

Using NPM, we can more easily view updates that depend on these modules.

npmWhat did they do?

NPM consists of three different components:

  • Website: www.npmjs.com/
  • Command line interface (CLI) : Developers use it to manage, install, update, and publish modules;
  • Registry: A large database of js modules shared by people

2. Install NPM

Install NPM from the Node.js site

Step 1: Install Node.js and NPM

Here is not specific to explain the installation process, there are many online. NPM is attached to Node. js and can be found at nodejs.org/en/download… Download and install Node.js.

Step 2: Test your installation

After installation, run Node -v. There is no error, the version number is success. If node.js is installed, NPM is automatically installed. Also run NPM -v to view the version number.

Step 3: If you need to update the NPM

NPM is updated much more frequently than Node, so the version of NPM shipped with node may not be the latest. You can download the latest VERSION of NPM using the following command:

npm install npm@latest -g
Copy the code

Here’s what that means

  • Install: indicates to install;
  • npm@latestUse:@Latest indicates the latest template. We download other modules in the same format.
  • -g: indicates global installation

Installation -g is a global installation and can be used at any command, such as:

npm i http-server -g
Copy the code

> We can use http-server on the command line because we configured environment variables.

/usr/local/bin/http-server -> /usr/local/lb/node_modules/http-server/bin/http-server

package.json

The best way to manage locally installed NPM packages is to create a package.json file.

Understand the package. The json

At the root of each project (a package downloaded on NPM, or any other NodeJS project), there is typically a package.json file that defines the various modules required for the project, along with the project’s configuration information (such as name, version, license, how to start the project, running steps, and other metadata). The NPM install command automatically downloads the required modules based on this configuration file.

A package.json file is a JSON object, and each member of that object is a setting for the current project. For example, name is the project name and version is the version. Minor version. Minor version “). It also plays multiple roles throughout the project lifecycle, developing, testing, and launching.

Package. The role of json

  • As a description file, it describes the packages that your project depends on
  • Allows us to use the “semantic versioning rule” (described below) to specify the version of your project dependencies
  • Make your build easier to share with other developers and easy to reuse

How to create package.json

1. Use the CLI client

npm init
Copy the code

This launches a command-line questionnaire that creates package.json in the directory where you launched the command.

2. Create default values

To get the default package.json, run NPM init with the –yes or -y flag:

 npm init -y
Copy the code

This method generates default values for package.json using information extracted from the current directory, skipping the step of answering questions.

3. Create it manually

Create a package.json file directly in the project root directory and enter the relevant content. For details, see package.json.

Detailed description of common fields in package.json

1, the name,

Mandatory field, the name of the current module \ package, must contain no more than 214 characters, cannot start with a “.”(dot) or an underscore (_), and cannot contain uppercase letters.

This name might be passed as an argument to require(), so it should be short, but clear.

2、 version

Required field, the current package version number, first build default 1.0.0.

Version must be resolvable by a Node-Semver module that NPM depends on. Defines the iteration schedule for the current project. (Follow the “big version. Minor version. Minor version format)

Most people don’t notice or care about the version number and use the product version number, or git Hashcode.

3, the description

Optional field, which must be a string. The description of the current package is a string. It helps people find this package when using NPM Search.

If there is no description information in package.json, NPM uses the first line of readme. md in the project as the description information. This description will help others to search for your project, so it is advisable to write a description.

4, the main

Optional field that specifies the entry file to load the project.

The default value for this field is index.js under the module root.

5, and scripts

Optional fields, scripts is a hash object composed of script commands that are executed during the different life cycles of the package. Key is the life cycle event and value is the command to run. Specifies the NPM command line abbreviation for running script commands. For example, start specifies the command to be executed when running NPM run start. We can customize running footstep commands as we want.

Reference: www.ruanyifeng.com/blog/2016/1…

Scripts sets the execution steps

  • 1) Run the echo XXX command

    1. Execute the file under node_modules/.bin

Why can it be implemented?

When I run NPM run, I automatically create a new Shell in which to execute the specified script command. Therefore, any command that a Shell (usually Bash) can run can be written into an NPM script. Node_modules /. Bin will be copied to the path of the current system, so all scripts in the node_modules/. Bin subdirectory of the current directory can be called directly with script names. You don’t have to add a path.

Such as:

We use Node to execute a Node.js service. The node + file can use Node server.js; We can also use webpack front-end files, webpack-dev-server, of course webpack and webpack-dev-server are the dependencies to install;

"scripts": {   
    "build": "webpack --mode=development"."dev": "webpack-dev-server --mode=development --contentBase=./dist"."server":"node app.js"
  }
Copy the code

We type NPM run server into the command line tool and node app.js will be called to run it for us.

Short form:

NPM start is NPM run start NPM stop is NPM run stoptestNPM is runtestNPM restart is short for NPM run stop && NPM run restart && NPM run startCopy the code

Common scripts —– Online collection transfer

// Delete the directory"clean": "rimraf dist/*"// Set up an HTTP service locally"serve": "http-server -p 9090 dist/"// Open the browser"open:dev": "opener http://localhost:9090"// Refresh in real time"livereload": "live-reload --port 9091 dist/"// Build the HTML file"build:html": "jade index.jade > dist/index.html"// Whenever the CSS file changes, redo the build"watch:css": "watch 'npm run build:css' assets/styles/"// Whenever the HTML file changes, redo the build"watch:html": "watch 'npm run build:html' assets/html", // Deploy to Amazon S3"deploy:prod": "s3-cli sync ./dist/ s3://example-com/prod-site/"// Build favicon"build:favicon": "node scripts/favicon.js"."start": "cross-env NODE_ENV=production node server/index.js".Copy the code

6, dependencies, devDependencies

Optional. The Dependencies field specifies the module on which the project runs, and devDependencies specifies the module needed to develop the project.

The value points to an object. Each member of this object, consisting of a module name and corresponding version requirements, represents the dependent module and its version range.

Package. json is not created by default and is generated when we install NPM to install a module.

npm install express
npm install express --save
npm install express --save-dev
Copy the code

The above code indicates that the Express module is installed separately,

  • If no parameter is specified, the installation is todependenciesProperties,
  • --saveParameter Indicates that the module is written todependenciesProperties,
  • --save-devIndicates that the module is written todevDependenciesProperties.

7, bundledDependencies

Optional field, other dependencies that are packaged when the package is published.

8 peerDependencies.

Optional fields, compatibility dependencies, if your project or module also relies on another module, but in a different version.

For example, your project relies on version 1.0 of module A and module B, and module A itself relies on version 2.0 of module B.

{
  "name": "chai-as-promised"."peerDependencies": {
    "chai": "1.x"}}Copy the code

The code above specifies that when the chai-as-Promised module is installed, the main program CHAI must be installed together, and the version of CHAI must be 1.x. If your project specifies a chai 2.0 dependency, an error will be reported.

9、 bin

Optional field. The bin field is used to specify the location of the executable file for each internal command.

For example, I used this earlier when I wrote about creating my own scaffolding. Juejin. Cn/post / 684490…

See step 3 of this article, Project creation, for details.

Create the /bin/www file in the project root directory

#! /usr/bin/env node
Copy the code

In the package. The json configuration

"bin": {"lee-cli":"./bin/www"
}
Copy the code

NPM link creates a shortcut connection by adding a global link to the value path of the property bin in the package

Executing lee-cli on the command line executes the bin/ WWW file. The process is:

In the example above, the WWW establishes the symlink node_modules/.bin/ WWW. Since the node_modules/.bin/ directory adds the system’s PATH variable at run time, these scripts can be invoked directly with commands without paths when running NPM.

10 and the config

The config field is used to output values to environment variables

{
  "name" : "package"."config" : { "port" : "8080" },
  "scripts" : { "start" : "node server.js"}}Copy the code

We can use it if we want to change it

npm config set package:port 80
Copy the code

11, engines,

Optional field that specifies the platform version on which the module is running, such as a version of Node or a browser, and optionally the applicable NPM version.

"engines" : { 
"node" : 
"> = 0.10.3 < 0.12"
} 
Copy the code

12, license

Optional field that defines the license that applies to the code described in package.json. Different protocols have different limits. Let users know what permissions they have to use your module and what restrictions there are on using it.

Choose alicense: choosealicense.com/

For example: MIT: maximum permission, others download your code can change your code, default installation value.

13, the author

Optional field, project developer.

14 and private

Optional field, Boolean value, private or not, NPM refuses to publish when set to true.

This is one way to prevent private packages from being published outside of the system. If you want to wrap a package that can only be published to a particular Registry (for example, an internal registry), you can use the following publishConfig dictionary to describe how to override the Registry configuration parameter at publish-time.

15 and keywords

The optional field, the item key, is an array of strings. It helps people find this package when using NPM Search.

16, OS

Optional field that specifies on what operating system can the module run

17, style,

Style specifies the location of the style file for use by the browser.

In the 18th and the repository

The package code can be stored in git or SVN. Git is available on Github

19, homepage

Optional field, no URL with protocol prefix such as http://.

Version issues:

Version: “1.0.0”

1.0.0:

The first change is incompatible with old code, a massive update, a new release;

The second indicates: added some functions, downward compatibility;

Number three: minor patches, bug fixes;

When we published the project, one disk used NPM + Git

  • usenpm version patchThis will change the third bit of the version; usegit tagThe version number on Git is automatically executed
  • usenpm version minorThe second version number of this change; Synchronize git versions.
  • usenpm version majorThis changes the version number first; Synchronize git versions.
NPM version [< newversion > | major | minor | patch | premajor | preminor | prepatch | prerelease | the from - git] major: Minor: Indicates the minor version number. Patch: indicates the patch number. Premajor: indicates the pre-major versionCopy the code

Git working directory not clean

git add .
git commit -m"Package. Json explanation." "
Copy the code

NPM Versin Monir -m" Add version number"

git push -u origin master
Copy the code

How are the rules made?

As a consumer, we can specify in the package.json file the level of updates we accept for this package (assuming we are currently relying on version 1.2.4) :

  • If you only want to accept the patch version update (that is, the last bit change), you can write:

    1.2 1.2 x ~ 1Copy the code
  • If you accept a minor version update (a secondary change), you can write:

    1. 1 x ^ 1Copy the code
  • If you can accept a major release update (naturally accept minor and patched changes), you can write:

    *
    x
    Copy the code

    To summarize: there are three types of version change, and whichever type of update you accept from a dependency package, you write the version number in the first place.

Release cycle and phase:

  • Alpha Alpha Phase 1 is generally for internal testing only
  • Beta-beta Phase 2 has eliminated most of the imperfections in the software, but there may still be defects and bugs, which are generally available for testing by specific groups of users;
  • γ -RC is the third stage, at this time the product is quite mature, only need to do further optimization in individual places can be released

Such as:

2.1.0-beta.1 Generally so that users will not install this, this can be used by inside, testers.

The version of the dependent package is faulty

The instance instructions
~ 1.2.3 Major version + Minor version + patch version; 1.2.3 <= version < 1.3.0;
~ 1.2 Major + Minor version; 1.2.0 <= version < 1.3.0
~ 1 The major version; 1.0.0 <= version < 2.0.0
symbol The instance Version range instructions
1.0.0 1.0.0 Lock version 1.0.0, which is required.
^ Will match the latest large version dependency package ^, ^ 0.2.3 >=1.2.3 <2.0.0, >=0.2.3 <0.3.0 X.x indicates that the latest version of 1.x.x (no later than 1.2.3, including 1.3.0) is installed, but 2.x.x is not installed, that is, the major version number is not changed during installation. It is important to note that if the major version number is 0, the behavior of the insertion number is the same as that of the tilde. This is because at this stage of development, even minor version number changes can cause incompatibilities in the program. (Main version)
~ will match the most recent minor version dependency package ~ 1.2.3 > = 1.2.3 < 1.3.0 The latest version of 1.2.x (no less than 1.2.3) is installed, but 1.3.x is not installed, that is, the major and minor versions are not changed during installation.
> = > = 2.1.0 > = 2.1.0 The value is greater than or equal to 2.1.0
< = < = 2.0.0 < = 2.0.0 Less than or equal to 2.0.0
laster Install the latest version
* > = 0.0.0 Any version
1.2.3-2.3.4 > = 1.2.3 < = 2.3.4

To distinguish the installationDependenciesanddependencies?

DevDependencies is a module that you need to install during development to improve your development efficiency, such as webPack, rollUp, less, Babel, etc. There is no need to install in a build environment.

The following libraries are recommended to install into devDependencies:

  • Unit test support (Mocha, CHAI);
  • Syntax compatibility (Babel);
  • Syntax conversion (JSX to JS, Coffeescript to JS, typescript to JS)
  • Program construction and optimization (Webpack, gulp, Grunt, uglifyJS);
  • CSS processor (postCSS, SCSS, Stylus);
  • Code specification (ESLint);

Dependency packages (specify, update, local, Use, Uninstall)

1. Install local dependency packages

npm install jquery
Copy the code

This command will create a node_modules directory in the current directory, and then download our specified package into this directory.

2, specify the installed version, you can use package name @ version number.

If the package name begins with @, it is a scope package.

NPM install [email protected] NPM install jquery@"> = 1.1.0 < 2.2.0"
npm install jquery@latest
Copy the code

After the update, the version number in Dependencies also changes.

3. Update dependency packages

npm update jquery
Copy the code

4. Use packages

let jquery = require('jquery');
Copy the code
<script src="/node_modules/jquery/dist/jquery.js"</script>Copy the code

6. Uninstall the dependency packages

npm uninstall jquery
Copy the code

Semantic versioning rules

Docs.npmjs.com/about-seman…

Github.com/npm/node-se…

Package. json Precautions

If you do not have a package.json file, install cannot be installed. If you do not have a package.json file, install cannot be installed

  • Name: All lowercase characters without Spaces. Use hyphens and underscores sequentially
  • Version: version number, following the semantic version rules described abovex.x.x

Other notes:

  • Adding Chinese comments will cause a compilation error

extension

other

1, We often exit the installation in the middle and continue the installation will report an error, this is because of the cache.

npm cache clean --force
Copy the code

2, NPX

NPX can execute node_modules/. Bin directly without having to configure scripts

If the module does not exist, it can be installed. After the installation, it will destroy itself to avoid installing the global module

References:

Cloud.tencent.com/developer/s…

Docs.npmjs.com/about-seman…

semver.org/lang/zh-CN/

Docs.npmjs.com/misc/semver…

www.ruanyifeng.com/blog/2016/1…