How to write your own package, and then publish and maintain the package?

Environmental preparation

Environment where node is installed

To learn npm package management, you must first install the Node.js environment. In this case, you can search and view the installation of relevant tutorials by yourself. I won't elaborate here

Update npm tool version

Node.js comes with npm, but generally the version of npm is lower than the latest version. You can manually update the version of npm to the latest version

npm install npm@latest -g

npm account registration

If we publish the package to npmjs, we need to have our own npm account, which you can use
npm official website Self registration for subsequent learning.

Basic use of npm

1, Experience initialization npm project

After preparing the environment, let's first experience the process of initializing the npm project. After entering the npm init command, enter the corresponding content according to the prompt. We don't need to enter any content here for the time being. Just press enter to keep it empty.

  1. Under the specified path, use the terminal tool to execute the following command to create a new folder and switch to the directory
    mkdir npmtest
    cd npmtest
    
  2. Execute the npm initialization command, and then press enter all the time. The following output will appear
    npm init
    
    /*
    This utility will walk you through creating a package.json file.
    It only covers the most common items, and tries to guess sensible defaults.
    
    See `npm help init` for definitive documentation on these fields
    and exactly what they do.
    
    Use `npm install <pkg>` afterwards to install a package and
    save it as a dependency in the package.json file.
    
    Press ^C at any time to quit.
    package name: (npmtest)
    version: (1.0.0)
    description: 
    git repository:
    keywords: 
    author: 
    license: (ISC)
    About to write to ***********\npmtest\package.json:
    
    {
      "name": "npmtest",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }
    
    
    Is this OK? (yes) yes
    */
    
  3. After executing the initialization command, a package.json file will appear in the project directory file, with the following contents:
     {
       "name": "npmtest",
       "version": "1.0.0",
       "description": "",
       "main": "index.js",
       "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1"
       },
       "keywords": [],
       "author": "",
       "license": "ISC"
     }
    
  4. The directory tree structure is as follows:
    ├─npmtest
    |  ├─package.json
    
  5. Through this process, we can see that using npm package to package the project is actually very simple, the management is also very simple, and the management of dependencies is also very simple. There is only one package.json file.

2, Configure basic user information

  1. Set and initialize the default user name, mailbox and license. After setting this, we don't need to set them according to the command line prompt
     npm set init.author.email "Fill in your email in double quotation marks"
     npm set init.author.name "Write your name in double quotation marks"
     npm set init.license "Fill in the certificate type in double quotation marks"
     // For example, the default information I set myself is as follows
     npm set init.author.email "897317986@qq.com"
     npm set init.author.name "plasma007"
     npm set init.license "MIT"
    
  2. We can now use the npm init -y command for fast initialization
     npm init -y
    
  3. We can see that in the package.json file, the value of author license is the default value we set.
     Wrote to ****\npmtest\package.json:
     {
       "name": "npmtest",
       "version": "1.0.0",
       "description": "",
       "main": "index.js",
       "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1"
       },
       "keywords": [],
       "author": "plasma007 <897317986@qq.com>",
       "license": "MIT"
     }
    

3, Create and publish your own package

In the previous steps, we have experienced that if we initialize the npm project, now we will create and publish our own package.

  1. Create a folder and open the path. It is recommended that the folder name be consistent with the package name (the package to be published cannot have the same name. Here, a different package name should be used to replace plasma007 my NPM test)
     mkdir plasma007-my-npm-test
     cd ./plasma007-my-npm-test
    
    The directory tree structure:
    ├─plasma007-my-npm-test
    |
    
  2. Create a simple script file lib/index.js (any name can be used as the entry file, generally the same as the package name or index), and write a simple function as follows:
    const printMsg = () => {
      console.log("This is a message from the demo package");
    }
    
    module.exports = {
      printMsg
    }
    
    The directory tree structure:
    ├─plasma007-my-npm-test
    |  ├─index.js
    
  3. npm initialization project
    npm init
    
    // Enter the project related information according to the prompt, and name it as the entered name. The package name can be modified in the later package.json configuration file
    package name: (Default folder name) plasma007-my-npm-test
    // The default version number is 1.0.0, as above
    version: (1.0.0)
    // Detailed description of the package
    description: This is my study npm First project attempt for package management 
    // The default entry file is index.js
    entry point: (index.js)
    // test command
    test command: 
    // The git warehouse address of the project, such as github, gitee, etc
    git repository:
    // keyword
    keywords: mytest
    // Project author name
    author: plasma007
    // License type of package, default ISC
    license: (ISC) MIT
    
    The directory tree structure:
    ├─plasma007-my-npm-test
    ├─lib
    |  ├─index.js
    ├─package.json
    
    
  4. After initializing the project successfully, you will be prompted that the relevant information has been written to / plasma007-my-npm-test/package.json. Press enter
    About to write to ****\plasma007-my-npm-test\package.json:
    
    {
      "name": "plasma007-my-npm-test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "plasma007 <897317986@qq.com>",
      "license": "MIT"
    }
    
    Is this OK? (yes) yes
    
  5. If you haven't logged in to npm account, you need to log in first. If the login fails, it may be the common problem list in the following text. 1. If you can't log in to npm, you can solve it according to the methods in it.
    npm login
    // Press the prompt to enter the user name and password, which will not be displayed when entering the password
    Username: plasma007 // Enter your account and password respectively
    Password:
    
  6. Publish the written package
    npm publish 
    // npm will prompt a lot of information. If there is no error and the last line is+ xxxx@1.0.0 It means the release is successful
    
  7. Next, verify whether your package has been successfully published. Create a new directory in another directory and open it
    mkdir testnpm
    cd ./testnpm
    
  8. npm installs the package just released npm install + package name. The package name is your own package name. Don't write it wrong.
    npm install plasma007-my-npm-test
    
  9. Create a test.js file and introduce the functions in the package
    import { printMsg } from 'plasma007-my-npm-test';
    
    printMsg()
    
  10. Modify the configuration in the package.json file, add a startup script, and modify the file type to module
    {
        ...,
        "script" : {
            "dev" : "node ./test.js"
        },
        "type" : "module"
        ...
    }
    
  11. Execute the script command, and the console will output This is a message from the demo package, indicating that the package published by yourself can be imported normally
    npm run dev
    
    // display
    > dev
    > node ./testnpm1.js
    
    This is a message from the demo package
    

NPM advanced

README file for package

  1. The file must be in the root path of the package project
  2. The file can only be updated with the package version update

package version update

npm version patch // If there is no pre release number, upgrade the trumpet directly. If there is a pre release number, remove it directly  
npm publish

The address after package publishing is https://npmjs.com/package/ Package name

Add ignore file

  1. Scheme 1: use the white list strategy to specify the packaged files in package and JSON, which can effectively prevent some documents that do not want to be published or unnecessary from being uploaded to the public warehouse due to negligence or other reasons
{
    ...,
    "files": [    "/lib"  ]  //It must be in /, otherwise * / lib will be recognized
    ...
}
  1. Scheme 2: use the. npmignore file to add the ignored file. The specified file name will not be packaged, but there are bug s. It is possible that some files will be packaged and published

script command parameters

To pass a parameter to the npm script, you need to add --, and then the JS script takes the value through the process.env. Parameter name, eg:

// When the script command is executed, the parameter name="plasma007" is appended
npm run dev -- name="plasma007"
// Extract parameters from script file
let name = process.env.npm_config_name;

Common error list

1. Unable to log in to npm

When using the npm login command, if the message prompted is npm notice Log in on https://registry.npm.taobao.org/ An error will be reported when logging in. At this time, we need to switch the NPM source back to the default source. The source switching command is as follows:

// Switch back to the default npm source
npm config set registry https://registry.npmjs.org/
// Switch to Taobao source
npm config set registry http://registry.npm.taobao.org/
// View current source
npm get registry 

Tags: Javascript node.js

Posted on Sat, 11 Sep 2021 17:38:29 -0400 by hyp0r