I. Introduction to NPM

NPM, fully known as Node Package Manager, is a Node.js-based Package Manager, which is the most popular and supports the most third-party modules in the entire Node.js community.

The original purpose of NPM:

It’s easier for JavaScript developers to share and reuse code.

NPM usage scenarios:

  • Allows users to obtain third-party packages and use them.

  • Allows users to publish and share their own packages or command-line programs.

NPM version Query the NPM -v

NPM install:

1. Install nodeJS

Since the new nodeJS version already integrates NPM, you can directly test the successful installation by typing NPM -v.

NPM install NPM -g

Ii. Working principle of NPM

Packages and modules

What is a package?

A package describes a file or a directory. The configuration of a package usually consists of the following:

  • A folder contains a package.json configuration file.
  • Contains the Gzip zip file (folder containing package.json files).
  • Parse the Gzip URL
  • Add url information for @ to the registry

Note that even if you never publish your public packages in the registry, you may still get many of the benefits of using NPM for all of these packages:

  • If you just plan to write add a node or /.
  • If you install it you also want to separate it into a tarball elsewhere after packing it

2. What is a module?

A template contains one or more packages through a DOM node in a configuration file. It usually consists of packages and configuration files and related module programs to perform one or more business function operations.

A module can be filled with any require() in a Node.js program. Here is an example of all things loading modules:

  • A folder package.json file contains a main field.

  • A folder named index.js file.

  • A JavaScript file.

3. The relationship between NPM packages and modules:

In general, js programs use require to load their modules to configure NPM packages in nodes. A module is not necessarily a package.

For example, some CLI packages contain only an executable command line interface in the JS program node and do not provide the main field. Then these packages are not modules.

Almost all NPM packages (at least, those node plans) contain many modules in them (since every file loaded require() is a module).

Almost all NPM packages are associated with multiple modules, because each file loads a module using require().

Load the context node node from the module file. Var req = require(‘request’) We might say, “The request module assigns to the variable req.”

4. NPM ecosystem:

The package.json file defines packages.

The node_modules folder is where the modules are stored. Easy for JS to find modules.

If you create a node_modules/foo.js file, use var f=require(‘foo.js’) to load the module. Foo.js is not a package because it does not have a package.json file.

If you don’t create the index.js package or the package.json file “main” field, even if you’re installing node_modules, it’s not a module because it doesn’t require().

use

npm init

NPM init is used to initialize a new package.json file. It asks the user a series of questions, and if you don’t want to change the default Settings, just press enter.

If -f (for force), -y (for yes) is used, then skip the questioning phase and generate a new package.json file directly.

$ npm init -y
Copy the code

npm set

NPM set is used to set environment variables

$ npm set init-author-name 'Your name'
$ npm set init-author-email 'Your email'
$ npm set init-author-url 'http://yourdomain.com'
$ npm set init-license 'MIT'Copy the code

This command sets the default value for the package.json author name, mail, home page, and license fields when executing NPM init. This information is stored in the ~/.npmrc file in the user’s home directory, so that the user does not have to enter each item. If a project has different Settings, you can run NPM config for that project.

npm info

The NPM info command displays detailed information about each module. For example, view the information for the underscore module.

$ npm info underscore
Copy the code

The above command returns a JavaScript object that contains the details of the underscore module. Each member of this object can be queried directly from the info command.

$ npm info underscore description

$ npm info underscore homepage

$ npm info underscore version

Copy the code

npm search

The NPM search command is used to search the NPM repository. It can be followed by either a string or a regular expression.

$NPM search < search term >Copy the code

npm list

The NPM list command lists all the modules installed for the current project in a tree structure, as well as the modules they depend on.

$ npm list

# With the global parameter, globally installed modules are listed
$ npm list -global

The # NPM list command can also list individual modules
$ npm list underscore
Copy the code

npm install

The command for using the NPM installation package is in the following format:

npm [install/i] [package_name]

Local mode and global mode

By default, NPM searches for or downloads packages from npmjs.org and installs them into the node_modules subdirectory of the current directory.

If you’re familiar with Ruby’s gem or Python’s PIP, you’ll notice that NPM behaves differently. Gems or Pips are always installed in global mode, making packages available to all programs, whereas NPM installs packages in the current directory by default. This reflects NPM’s different design philosophy. If you install packages globally, you can provide a degree of program reuse and avoid multiple copies of the same content, but the downside is that it is difficult to handle different version dependencies. If you install the package in the current directory, or locally, you don’t have the problem of different programs relying on different versions of the package, and you reduce the API compatibility pressure on the package author, but the disadvantage is that the same package can be installed many times.

When we use supervisor, we use the NPM install -g Supervisor command to install supervisor in global mode.

One thing to note here is that Supervisor must be installed globally, and if you don’t, the error command will prompt you to install it globally. If you do not want to install to the default global directory, you can also modify the global directory to the current directory. NPM config set prefix “Path”

The Supervisor helps you do this by monitoring your driver of the code and automatically restarting Node.js.

In general, global installation only applies to tool modules, such as ESLint and gulp. Most of the time, the global schema is used not because it is likely to be used by many programs to reduce multiple copies, but because the local schema does not register the PATH environment variable.

“Local installation” means downloading a module to the node_modules subdirectory of the current project, and then calling the module only from within the project directory.

# Local install
$ npm install <package name>

# global install
$ sudo npm install -global <package name>
$ sudo npm install -g <package name>
Copy the code

NPM Install also supports direct entry of Github codebase addresses.

$ npm install git://github.com/package/path.git
$ npm install git://github.com/package/path.git# 0.1.0 from
Copy the code

Before installing, NPM install checks whether the specified module already exists in the node_modules directory. If it exists, it is not reinstalled, even if a new version of the remote repository is available.

If you want NPM to force a module to be reinstalled regardless of whether it was installed, you can use the -for –force arguments.

$ npm install <packageName> --force

Copy the code

Install different versions

The install command always installs the latest version of a module, and if you want to install a specific version of a module, you can follow the module name with @ and the version number.

$NPM install sax@latest $NPM install [email protected] $NPM install sax@"> = 0.1.0 from < 0.2.0"
Copy the code

The install command can use different parameters to specify which dependencies the installed module belongs to, that is, which entry in the packes.json file.

- Save: The module name is added to Dependencies, which can be simplified to the -s argument. - save-dev: the module name is added to devDependencies and can be simplified to the -d argument. $ npm install sax --save $ npm install node-tap --save-dev# or
$ npm install sax -S
$ npm install node-tap -D
Copy the code

Dependencies rely on

This can be said to be a core content of our NPM, dependency management, the content of this object is the JS module package that our project depends on. The following code indicates that we rely on the markdown-it package. The version is ^8.1.0, which means that the minimum version is 8.1.0. If the package is updated, NPM will download the latest package for us when we use the NPM install command. When someone references our package, the dependencies in the package are also downloaded.

"dependencies": {
    "markdown-it": "^ 8.1.0"
}
Copy the code

DevDependencies Develops dependencies

NPM does not download the packages that we reference in devDependencies. NPM does not download the packages that we reference in devDependencies.

"devDependencies": {
    "autoprefixer": "^ 6.4.0". 0","babel-preset-es2015":"^ 6.0.0","babel-preset-stage-2":"^ 6.0.0","babel-register":"^ 6.0.0","webpack":"^ 1.13.2","webpack-dev-middleware":"^ 1.8.3","webpack-hot-middleware":"^ 2.12.2","webpack-merge":"^ 0.14.1","highlightjs":"^ 9.8.0"}Copy the code

When you have a complete package.json file, you can show the basic information about the module and the packages it depends on. We can easily download the package required by this module through NPM install.

NPM install installs the Dependencies field and all modules in the devDependencies field by default. If you use the –production parameter, you can install only modules in the Dependencies field.

$ npm install --production
# or
$ NODE_ENV=production npm install
Copy the code

Once a module is installed, it can be loaded in code with the require command.

var backbone = require('backbone')
console.log(backbone.VERSION)

Copy the code

npm run

NPM can be used not only for module management, but also for executing scripts. The package.json file has a scripts field that can be used to specify script commands to be invoked directly by NPM.

package.json

{
  "name": "myproject"."devDependencies": {
    "jshint": "latest"."browserify": "latest"."mocha": "latest"
  },
  "scripts": {
    "lint": "jshint **.js"."test": "mocha test/"}}Copy the code

Scripts script

NPM run dev = nodebuild /dev-server.js = nodebuild /dev-server.js = nodebuild /dev-server.js = nodebuild /dev-server.js The purpose of using scripts is to merge some code to be executed together and use NPM run to run it quickly and easily. NPM run is short for NPM run-script. The former is usually used, but the latter better reflects the nature of the command.

/ script"scripts": {
    "dev": "node build/dev-server.js"."build": "node build/build.js"."docs": "node build/docs.js"."build-docs": "npm run docs & git checkout gh-pages & xcopy /sy dist\\* . & git add . & git commit -m 'auto-pages' & git push & git checkout master"."build-publish": "rmdir /S /Q lib & npm run build &git add . & git commit -m auto-build & npm version patch & npm publish & git push"."lint": "eslint --ext .js,.vue src"
}

Copy the code

NPM run, if run without any arguments, will list all script commands that can be executed in package.json. NPM has two built-in command abbreviations, NPM test is equivalent to running NPM run test, and NPM start is equivalent to running NPM run start.


"build": "npm run build-js && npm run build-css"
Copy the code

Run NPM run build-js and then run NPM run build-css with && between the two commands. If you want two commands to be executed in parallel, you can use an ampersand between them.

The commands written in the scripts property can also be written as bash scripts directly in the node_modules/.bin directory. Here is a bash script.

Pre – and post- scripts

NPM run provides pre- and post- hooks for each command. NPM run Lint: NPM run lint: NPM run lint: NPM run lint: NPM run lint: NPM run lint: NPM run lint: Finally, execute NPM run postlint.

{
  "name": "myproject"."devDependencies": {
    "eslint": "latest"
    "karma": "latest"
  },
  "scripts": {
    "lint": "eslint --cache --ext .js --ext .jsx src"."test": "karma start --log-leve=error karma.config.js --single-run=true"."pretest": "npm run lint"."posttest": "echo 'Finished running tests'"}}Copy the code

The code above is an example of a package.json file. If NPM test is executed, the corresponding commands are executed in the following order.

pretest

test

posttest

If the execution goes wrong, the scripts next in line are not executed, i.e., if the prelint script goes wrong, lint and postLint scripts are not executed.

npm bin

The NPM bin command displays the.bin directory of the Node module’s executable script relative to the current directory.

# project root
$ npm bin
./node_modules/.bin
Copy the code

Creating global links

NPM provides an interesting command, NPM link, which creates symbolic links between local and global packages. We said that packages installed using global mode cannot be used directly through require. However, this limitation can be broken with the NPM link command. For example, we have already installed Express via NPM install -g Express and run the command in the project directory:

npm link express ./node_modules/express -> /user/local/lib/node_modules/express

Copy the code

We can find a symlink in the node_modules subdirectory that points to packages installed globally. In this way, we can use global packages as if they were local packages.

In addition to linking global packages locally, you can use the NPM link command to link local packages globally. To do this, run the NPM link command in the package.json directory. If we were to develop a package, this approach would be very convenient for testing across different projects.

Create a package

Packages are further abstractions based on modules. Node.js packages are similar to C/C++ libraries or Java or.NET libraries. It encapsulates a separate function for publishing, updating, dependency management, and version control. Node.js implements the package mechanism according to the CommonJS specification, and develops NPM to solve the needs of package publishing and obtaining. The node. js package is a directory that contains a package description file in JSON format, package. JSON. Packages that comply strictly with the CommonJS specification should have the following characteristics:

. Package. json must be in the top-level directory of the package; . Binaries should be in the bin directory; . JavaScript code should be in the lib directory; . The document should be in doc; . Unit tests should be in the test directory.

Node.js doesn’t have such strict package requirements, as long as package.json is in the top-level directory and complies with some specifications. To improve compatibility, however, we recommend that you follow the CommonJS specification strictly when creating your package.

We can also encapsulate folders as modules, known as packages. A package is usually a collection of modules that provide a higher level of abstraction on top of the modules, equivalent to a library of fixed interfaces. By customizing package.json, we can create more complex, complete, and spec compliant packages for distribution.

When calling a package, Node.js will first check the main field of the packGage. Json file as the interface module of the package. Will try to find index.js or index.node as the interface to the package.

Package. json is a package.json file specified by CommonJS to describe packages. A package.json file that is fully compliant with the specification should contain the following fields:

Name: indicates the package name. It must be unique and consists of lowercase letters, digits, and underscores (_). It cannot contain Spaces.

Description: A brief description of the package.

Version: version string that conforms to the semantic version recognition specification.

Keywords: keyword group, usually used in searches.

Maintainers: Array of maintainers. Each element contains name, email(optional), and Web (optional) fields.

Ficol3: An array of contributors, in the same format as Maintainers. The package author should be the first element in the contributor array.

Bugs: The address where bugs are submitted. This can be a web address or email address.

Licenses: Array of licenses, each element to contain

Type (the name of the license) and URL (the address that links to the license text) fields.

Repositories: Repository managed address array, each element containing type (repository type, such as Git), URL (repository address), and Path (relative to repository path, optional) fields.

Dependencies: An associative array of package names and version numbers.

The release of the package

Using NPM init, you can generate a standards-compliant package.json based on interactive responses. Create an index.js interface to the package, and you have a simple package. Before publishing, we also need to obtain an account to maintain our own package in the future. Use NPM adduser to complete the account creation as prompted.

When you’re done, you can use NPM whoami to check if an account has been obtained.

Next, run NPM publish in the package.json directory. After a while, you’ll be ready to publish. Open your browser and go to search.npmjs.org/ to find the package you just published. We can now install it on any computer in the world using the NPM install neveryuModule command.

If your package has future updates, simply change the version field in the package.json file and re-use the NPM publish command. If you are not satisfied with a published package, you can use the NPM unpublish command to cancel the publication.