npm is the package manager for Node.JS. When developing Node.JS, it is often used to install/uninstall packages. In fact, it is also done by publishing a package.
Configure package.json
To package a program, you must first set up various settings, which are specified by package.json in the root directory of the package. The content of package.json must be in strict JSON format, that is:
1. Strings should be enclosed in double quotes, not single quotes;
2. The attribute name must be double quoted;
3. Do not add a comma after the last attribute.
There are many attributes of configuration objects, please refer to here for details. Here are some commonly used items:
1.name: The package name cannot be repeated with existing packages.
2.version: version number.
3. Description: A brief introduction.
4.author: Author information. Contains three attributes: name, email, and url.
5.bin: If there is an executable file in the program (mainly called from the command line), specify it here and you can specify multiple files.
6.main: The program entry when calling this package using require.
7.dependencies: dependent package, you can specify the version number.
After configuring package.json, you can package and install it locally to test whether the program is operating normally. The installation command is:
The code copy is as follows:
npm install <local path>
In addition, there is another unspoken rule to note that if you want the executable program in the package to run in the Node.JS environment, then please add a line like this in front of the program entry file:
The code copy is as follows:
#!/usr/bin/env node
Without this line, it will be turned on in the system default mode, rather than running in the Node.JS environment.
Register an npm account
To publish the package to npm, you also need to register an account first. npm does not provide a web version of the registration wizard. Registration must also be carried out through the command line:
The code copy is as follows:
npm adduser
After executing this command, a prompt for entering the user name, email, and password will appear in turn. After entering, you can wait for a while.
Publish packages
After the preparations are done, you can publish the package by executing the following command:
The code copy is as follows:
npm publish <local path>
If you want to update the package, just modify the version number in package.json and then execute the release command again.