I don’t believe you know all these NPM instructions


I don't believe you know all these NPM instructions


NPM as a front-end tool, it must be well mastered, in the usual development, the most used should benpm installHowever, such a powerful tool will certainly do more than that.

Now I sort out what I know about NPM. Most of them are usually used. The integration is not only convenient to find out, but also the good qualities that young pioneers should possess as the successors of socialism remind me to make due contributions to the society. Writing this, I can’t help but look down, the chest red scarf seems to be more red, the sun father-in-law seems to be smiling at me and nodding.

Before we start, we have to say that collections are constantly updated, because knowledge is always added. However, it will not be updated frequently, and it will be saved to play again,Keep updating, suggest collectionThe article will be put in my blog collection, which will be updated quickly.

One more word, windows students can try the windows command line artifact cmder, which can reduce many strange errors when using Windows native command line.

Command set

It is strongly recommended that cnpm should not be used because there will be various strange bugs. Compared with cnpm, setting registry for NPM is a good choice,NRM is a better choice

npm initCreate Foundation package.json

#Can complete the creation interactively with the command line
npm init
#Skip the interaction directly and create it with default value package.json
npm init -y

npm publishPublish NPM package

Here only lists the steps of publishing, specific how to write the NPM package, you can search the relevant content on the Internet, all kinds of bigwigs have sorted out a lot, bloggers will not play tricks in this class.

It should be noted that,We need to switch the registry to the NPM source firstHowever, if Taobao cannot be used, Taobao synchronizes the national and regional resources of the NPM package, and the actual resources are still from NPM. Therefore, you need to publish them to NPM first, and then wait for Taobao to synchronize automatically (by the way, you can brush a wave of downloads).

#Switch registry to NPM
nrm use npm

#Using NPM publish for the first time
#If you are using NPM publish for the first time, you need to add an account
npm adduser

#Not the first time to use NPM publish
#Login account, this step can actually do not need to do, directly look at whoamI
npm login

#View current account
npm whoami
npm publish

npm viewView details of a library

It is very convenient for libraries with tags. You can view the corresponding tag names. If you need to install a specific tag library, you can use thenpm install ${packageName}@${tag}

npm view @vue/cli

#After viewing the view, install the specified tag
npm install -D @vue/[email protected]

npm rootGets the node of the current project_ Modules path

It can be used in the command-line class library to look up the node_ And return the absolute path.

But there are also bugs if you use it in an empty foldernpm rootThe node is added directly to the current path_ Modules return,Even if there is no node in your directory_ Modules folder

npm root

For example, if you are in a deep path, you need to use thenode_modules/.binWe have two ways to find the directory

const moduleRootPath = path.join(process.cwd(), "node_modules");
const moduleRootPath = execa.sync("npm", ["root"]);

npm listView globally installed modules

npm list -g --depth=0

npm cacheClear NPM cache

report errorsnpm resource busy or lockedWhen, or other inexplicably wrong time, you can try.

#Force table forces cache clear
npm cache clean --force

npm versionQuick change project version

How to modify the version number of a project correctly? Is manual modification a little low? Here’s how to correct the version number.

We mentioned the NPM version rules above, and we will revisit them heremajor.minor.patch-preThere is a pre in the back. We take it as a temporary version. We don’t mention it above because the temporary version is rarely used.

#Gets the dependent version of the current project
npm version

#Modify the current project version to 1.1.5
npm version 1.1.5

The following is the correct version of the pose, it should be noted thatnpm version prereleaseThis is the instruction to modify the incremental temporary version.

#Upgrade major version 1.1.5 - > 2.0.0
npm version major
#Upgrade minor version 1.1.5 - > 1.2.0
npm version minor
#Upgrade patch version 1.1.5 to 1.1.6
npm version patch

#Upgrade temporary version 1.1.5 - > 2.0.0-0 of major version
npm version premajor
#Temporary version 1.1.5 to 1.2.0-0
npm version preminor
#Upgrade the temporary version of patch version 1.1.5 to 1.1.6-0
npm version prepatch

#Do you think you can increment the temporary version number by re executing NPM version pre *?
#No, all pre * temporary versions are incremented by the following command
npm version prerelease

In a word, you can also change the version with instructions, but you need to use theyarn version --new-version patchnothing more.

Node runtime memory overflow

On a computer with small memory, you may encounter the scenario that memory overflow causes the program to be killed--max-old-space-sizeMaybe we can solve this problem.

  "scripts": {
    "start": "node --max-old-space-size=4076 index.js"

Of course, if package.json There are a lot of commands in scripts. You need to add this instruction everywhere. The issue has already mentioned this problem. Maybe the version after node will solve this problem.

Add max-old-space-size to npmrc

In addition, we can not only add in scripts, but also in the execution command. As follows, an execution file under the bin directory of the command-line class library.

#!/usr/bin/env node --max-old-space-size=4096

const cli = require("../src").default;

What is NPM scope @?

When installing the dependency, we found that the dependency has a prefix@? This is the scope mechanism of NPM, which can be understood as an organization, such as@types/node@vue/cli, front@They are all organizations. Only package managers can upload packages to the corresponding scope. If you want to publish@types/helloNo, because you don’t@typesPermission for.

How to release the tape@What about prefix items? You must apply for the corresponding one in the NPM management interface@${scope}Yes, as shown in the figure below.

I don't believe you know all these NPM instructions

NPM version number Description

First of all, for general knowledge, the version number rule of NPM ismajor.minor.patch, which represents major version, minor version and patch version. When releasing, we need to follow the following principles.

  1. If you just fix the bug, update itpatch
  2. If new features are added, but are backward compatible, they are updatedminor
  3. If there is a big change, downward incompatibility, need to updatemajor

Those who can see what they mean will not be mentioned here, for example1.1.0>1.1.0>=1.1.0<1.1.0<=*It’s very special.


~1.1.0Can be matched to1.1.n

~1.1Can be matched to1.1.n

~1Can be matched to1.n.n


Start with the leftmost non-zero number in the version number, and the number on the right can be any number.

^1.1.0Can be matched to1.n.n

^0.1.0Can be matched to0.1.n


Latest is a special version number, which we mentioned abovenpm viewYou can try itnpm view @vue/cliYou can seedist-tagsThere are two,latestandnextIf we do not specify a tag when publishing a package, all the packages are published by defaultlatest

And if we set the dependent version tolatestThat means we install it every timelaetstThe latest version.

howevernextHow did it happen? We cannpm publishWhennpm publish --tag nextThat’s right. In this way, the sub publishing project will have one more tag.

During installation, unless otherwise specifiednpm install @vue/[email protected]Otherwise, they will not go under the tag.

NPM scripts hook script hook

NPM hook can be divided into two types: pre and post. Pre means execution before instruction and post means execution after instruction.

NPM has the following built-in instructionsstartstoptestrestartversioninstallpublishWhat do built-in instructions mean? That is, it can be passed directlynpm start, rather thannpm run startImplemented.


I’d like to talk about a few of them, because they all have similar instructions. You can add a pre or post before them. You can copy the following instructions to your package.json Inside, and then run the correspondingnpm startnpm testnpm stopWait, try.

It should be noted that,npm versionandnpm run versionIt’s different,npm versionWe mentioned earlier that the version can be set, andnpm run versionIt’s just a simple running instruction.

  "prestart": "echo prestart",
  "start": "echo start",
  "poststart": "echo poststart",

  "prestop": "echo prestop",
  "stop": "echo stop",
  "poststop": "echo poststop",

  "pretest": "echo pretest",
  "test": "echo test",
  "posttest": "echo posttest",

  "prerestart": "echo prerestart",
  "restart": "echo restart",
  "postrestart": "echo postrestart",

  "preversion": "echo preversion",
  "version": "echo version",
  "postversion": "echo postversion"

Just go through the head above. There are special usages here. You can customize the instructions and add the prefixes of pre and post.

Of course, you can’t use it herenpm helloAnd use itnpm run helloYes.

  "prehello": "echo prehello",
  "hello": "echo hello",
  "posthello": "echo posthello"


Let’s talk about two special instructions,npm installandnpm publishIn addition to prefixes of pre and post, these two have several hidden hooks.

Let’s talk about it firstnpm installAs you can see below, in addition topreinstallandpostinstallIn addition to the implementationprepublishandprepareHowever, only hook is given here, and the actual application scenarios play their own roles.

  "preinstall": "echo preinstall",
  "install": "echo install",
  "postinstall": "echo postinstall",
  "prepublish": "echo prepublish",
  "prepare": "echo prepare"

Let’s have a looknpm publishThis is more useful. For example,prepublishOnlyThis hook can be executed before publishing, such as project packaging or compilation, so as to prevent forgetting to compile and publish directly.

In addition, you can also use thepostpublishTo upload package information to database, etc.

  "prepublish": "echo prepublish",
  "prepare": "echo prepare",
  "prepublishOnly": "echo prepublishOnly",
  "prepack": "echo prepack",
  "postpack": "echo postpack",
  //It will not be executed until it is published successfully
  "postpublish": "echo postpublish"

npm scripts &、&&、|、||

First of all, to distinguish, & & and |, belong to a group of logical identifiers, while | and |, belong to another group and belong to Linux functions.

| &

Here, the front-end students may not know much about first, | is a pipe, and a single & means putting instructions into the background.

#| pipeline
#Get test.txt  File content of
#And pass the content to less for easy browsing
#Less is the instruction of Linux, you can browse files at will
cat test.txt | less

The next command, front-end students may not understand, the server side students need to know some.

such asnpm run startAfter the services are started, they are directly hung on the terminal foreground.

What do you mean hanging at the front desk? After the service is started, we can try typingls lOr other instructions, you can find that there is no output in the console.

I don't believe you know all these NPM instructions

But if you runnpm run start &Start the service in the background. If you enterlsOr other instructions. You can see that the console has output.

Don’t worry about the previous output, which is the output of Vue cli service, which is directly output to the screen.

I don't believe you know all these NPM instructions

Now that I’m here, let’s talk about some common Linux instructions.

#Hang the service in the background
npm run service &
#View services hanging in the background
#A service with ID will be returned, as follows
# [1]  + 1967 running    npm run service
jobs -l
#Kill services running in the background
kill 1967

Interested students can go to understand the following Linux instructions.

#Switch a background running or suspended service to the foreground
#Running suspended services in the background
#It also hangs the service to run in the background
#You can also query through jobs and stop with kill
#But the log cannot be queried
#Therefore, in node, we use PM2 to suspend the task
nohup npm run service &

Of course, in addition to starting the service and hanging in the background, the command has other uses. For example, you need to start a service, but you just want to run the command,npm run script1 & npm run script2 &The two instructions will run synchronously because they are both hung in the background.

|| &&

These two are the logical operators we are familiar with. |||||||||||||||||||||||process.exit(1);, then execute the next, & & indicates that the next is executed only after the previous run is successful.

#Execute test and log if an error is thrown
npm run test || npm run loginfo
#Execute install and then start
npm run install && npm run start

What is NPX? I also want to use my own library

What is NPX? NPX can understand the idiom FA Tang. The logic behind it is the same. Usually there are two usages.

In the project package.json Use in

Suppose the project package.json As follows, when you want to executetscYou need to write it in scripts./node_modules/.bin/tsc --project ./

  "scripts": { "build:ts": "./node_modules/.bin/tsc --project ./" },
  "devDependencies": { "typescript": "^3.7.4" }

But using NPX can be omittednode_modules/.bin/A long list, as follows.

  "scripts": { "build:ts": "npx tsc --project ./" },
  "devDependencies": { "typescript": "^3.7.4" }

Ensure that the latest script code is executed

When NPX is used in the project creation, NPM will download the library to store the temporary files, and delete them after the execution, which can ensure that the latest code is available at each run time.

npx create-react-app my-react-appIs that familiar? We want to write our own library with NPX is also very simple, as long as the package.json The configuration is as follows

  "name": "@scope/my-cli",
  "bin": {
    //No, this is the original usage of the library
    "my-cli": "bin/index.js",
    //Here is the code that NPX actually runs
    //We just keep the key and the packpage.name  Just the same
    "@scope/my-cli": "bin/index.js"

Next, publish your library and use itnpx @scope/my-cli hello, which is equivalent to a global installation@scope/my-cliRe executionmy-cli hello

Remove all globally installed modules

Use it carefully. Don’t use it unless you know what you’re doing

rm -rf /usr/local/lib/node_modules

Haoku recommendation

Ranking regardless of order, according to the memory of bloggers to record. Among them, there are command-line tools and three-party libraries that are easy to use. Most of them will not have the three-party libraries of the mainstream three frameworks (you know more than I do), and the node class library will be the main one.

Yarn dependency processing tool

There are so many things that are easy to use, but most people should use them. Benchmarking NPM can better handle project dependencies (but it is also found that NPM can be successfully installed, but yarn installation will report errors).

Throw the order, a word is to rush.

npm install yarn -g

#Installing devdep dependencies
yarn add -D @types/node
#Installing dep dependencies
yarn add axios
#Installing peerdep dependencies
#Peerdep dependency means that if you install me, you need to install XXX as well
yarn add -P vue
#Global installation dependencies
yarn global add @vue/cli

Mirror config China automatically configure national regional image

When downloading some libraries, it is found that even when the registry is configured, the download is still very slow, and even does not move for half a day? You may need this.

This library will automatically configure the address of many third-party libraries (e.g. electronic) to the national region image. Although it can be manually configured when necessary, what kind of bicycle is needed if there is one key operation! Download speed swish.

npm install -g mirror-config-china

NRM management registry

When you often need to switch the registry source (for example, you need tonpm publishCode, in this case, you need to switch to the NPM starting source). This tool can help.

npm install -g nrm

#Add NPM registry to NRM
nrm add npm http://registry.npmjs.org
#Add Taobao registry to NRM
nrm add taobao https://registry.npm.taobao.org
#Register using Taobao
nrm use taobao
#Register using NPM
nrm use npm

HTTP server quick start static service

It is very convenient to start a static service locally. Of course, there are many parameters. I will not do more demonstration here. I will just make a suggestion. For details, please refer to the following documents.


npm install -g http-server

For example, when you are happy to develop a project, package it to dist, and want to see how it works, you can go to the dist folder and start ithttp-serverService, he will default toindex.htmlStart the static service as an entry point and listen for file changes.

cd dist

NVM manages multi version nodes

Although it may be rare, you will still encounter the problem of running different versions of node on the same computer. This library can solve this problem.


#View the current node version in use
nvm current
#Install the specified version of node
nvm install 12.14.0
#Switch node version
nvm use 12.14.0
#Run with node version 12.14.0 index.js
nvm run 12.14.0 index.js


Recently, the rate of hair loss is similar to that of Ruixing coffee, and the forgetfulness is also growing. I often forget what I was going to do just by writing code. I was able to focus on a thing for four or five hours. Now it’s easy to get distracted. I wonder if I’m old. I’ve never panicked about my age before, but I’m looking at the excellence of the company The new generation will inevitably have some anxiety. How can ability not anxious? It’s not a job of forgetting to eat and sleep, but should make yourself an irreplaceable person. Feelings are the same, so is work.

This is not a hot spot. I think we all know more or less about the news of situ Zhengmei. It’s not too much to say that it is the fall of genius. Therefore, we should pay more attention to our body in addition to the technical details. There are many opportunities to make money, but only a healthy body can support your great ideal.

PS1: after I finished writing, I found that I didn’t know much about it. I wrote a lot of miscellaneous things. If you have private goods, you can share them with me secretly. I’ll try to sort them out and add them, crab.

PS2: a little bit of a headline party,Found that the amount of carefully written articles reading than the interview articles (refers to some), the heart imbalanceIf you know all about it, please join the group and mock me.


Code is life. I love it.

Technology is changing
The mind is always online
The road ahead is long
I'll see you next time

I am here [email protected] Welcome to play with me.

Welcome friends to join me directly, pull you into the group to learn the front end together, remember to note where you see my article Oh ~

I don't believe you know all these NPM instructions