Register an NPM account

  1. Sign up for an account at https://www.npmjs.com.

Start developing an NPM package

Initialize the warehouse

  1. All NPM packages need to be initialized, which is the package.json file we see here.
  2. Create an empty folder like:
  3. Go to the terminal of the file directory and execute:npm initCommand.
npm init
Copy the code

The terminal prompt will ask you to enter the version number, author, description, entry script, and so on. Select all defaults for testing purposes. When done, a package.json file is generated:

{" name ":" test - the module ", "version" : "1.0.0", "description" : "' NPM test", "main" : "index. Js", "scripts" : {" test ": "echo \"Error: no test specified\" && exit 1" }, "author": "lwh", "license": "ISC" }Copy the code

Entry file, also known as the main entry file

Json file entry file refers to index.js, so we can create a new js file in the same directory. We can export a Hello World function first. As follows:

   function hello(){
       console.log('hello npm');
   }
   exports.hello=hello;
Copy the code

Testing phase

  1. Create folders under files and directoriesnode_modulesAnd create a new folder under this directory as the package name. Such as:test-module.
  2. willindex.jsFile move totest-moduleDirectory, and thennpm init.
  3. Create a new one under the root of your projecttest.jsFile with the following code:
  var hello =require('test-module');
  hello.hello();
Copy the code
  1. The project file directory is:
Npmtest // Project root directory node_modules // package directory test-module // plugin folder index.js package.json test.js // Test JS file package.json // configuration fileCopy the code
  1. The terminal returns to the project directory and executesnode test.js, terminal outputhello npmIt is running successfully.

Publish to NPM

  1. The terminal opens to the plug-ins foldertest-modulesDirectory executionnpm adduserEnter the user name, password, and email information of NPM as prompted.
  2. Publish NPM package executionnpm publishThen you can find the package on NPM.

Install using the package you just uploaded

  1. Create a folder and execute it on the terminalnpm init.
  2. Terminal execution:npm i test-modules --saveYou cannode-modulesSee this package in directory.
  3. Create a new one under the root of your projecttest.jsFile with the following code:
  var hello =require('test-module');
  hello.hello();
Copy the code

The terminal executing Node test.js should see hello NPM.

Update the NPM package

  1. The terminal opens the plug-in file in the directory such as test-modules.
  2. Run the update againnpm publishThe command is OK and needs to be modifiedpackage.jsontheversionThe value must be greater than the current version; otherwise, an error will be reported. As follows:

Delete the NPM package

  npm unpublish --force
Copy the code