I don’t believe these NPM instructions. You know all about them


I don't believe these NPM instructions. You know all about them


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

Now I sort out what I know about NPM, most of which are usually used. Integrating them is not only convenient to find, but more importantly, as the successor of socialism, the good qualities of young pioneers are always reminding me to make due contributions to the society. Writing about this, I can’t help but look down. The red scarf on my chest seems to be more red, and the sun seems to be smiling and nodding to me.

Before we start, let’s say that the collection will keep updating, because knowledge is always replenished. But they don’t update frequently. They usually save a lot of money and put it back,Keep updating, suggest collection, articles will be put in my blog anthology, 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 not to use cnpm. There are all kinds of strange bugs. Compared with cnpm, setting registry for NPM is a good choice,Using NRM is a better choice

npm initCreate Foundation package.json

#Will use the command line to create interactively
npm init
#Skip interaction directly and create with default value package.json
npm init -y

npm publishPublish NPM package

Here are only the steps of publishing, and how to write NPM packages. You can search the relevant content on the Internet. The big guys have sorted out a lot, and the bloggers will not be here.

It should be noted that,We need to switch registry to the starting source of NPM firstInstead of using Taobao, Taobao synchronizes the national resources of NPM package. The actual resources are still from NPM, so you need to publish them to NPM first, and then wait for Taobao to synchronize automatically (by the way, you can get 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 using NPM publish for the first time
#Log in to your account. You don't need to do this step. Just look at whoamI
npm login

#View current account
npm whoami
npm publish

npm viewView a library’s details

It’s very convenient for libraries with tags. You can view the corresponding tag name. 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. It will look up the node_ The path to modules and returns the absolute path.

But there is also a bug, if you use it in an empty foldernpm rootThe node will be added directly to the current path_ Modules returns,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/.binThere are 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 you make mistakes, or when you make mistakes, you can have a try.

#The force table forces the cache to be cleared
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 modify the version number correctly.

We mentioned the version rule of NPM above, so let’s talk about it againmajor.minor.patch-preThere is a pre in the back. We take it as a temporary version, but 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 posture, need to pay attention to isnpm 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 - > 1.1.6
npm version patch

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

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

By the way, yarn can also change the version with commands, but you need to use theyarn version --new-version patchnothing more.

Node runtime memory overflow

On the computer with small memory, you may encounter the scene 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 you say package.json There are many commands in scripts in. You need to add the command in each place. Issue has mentioned this problem. Maybe the version after node will solve this problem.

Add max-old-space-size to npmrc

In addition, we can add not only scripts but also execution commands, as follows: an execution file in 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 @?

It is found that the dependency has a prefix when installing the dependency@? This is the scope mechanism of NPM, which can be understood as an organization, such as@types/node@vue/cli, front@All are organizations. Only the package manager can upload the package to the corresponding scope. If you want to publish it@types/helloYou can’t because you don’t have one@typesPermission for.

How to release the tape@What about prefix items? You must first apply for the corresponding@${scope}Only then, as shown in the figure below.

I don't believe these NPM instructions. You know all about them

NPM version number Description

Let’s start with general knowledge. What is the version number rule of NPMmajor.minor.patch, representing 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 downward compatible, update themminor
  3. If there is a big change, downward incompatibility, need to updatemajor

Those who know what they mean at a glance will not be mentioned here, for example1.1.0>1.1.0>=1.1.0<1.1.0<=*It’s quite special.


~1.1.0Can match to1.1.n

~1.1Can match to1.1.n

~1Can match to1.n.n


Starting from the leftmost non-zero number in the version number, the number on the right can be any number.

^1.1.0Can match to1.n.n

^0.1.0Can match to0.1.n


Latest is a special version number, which we mentioned abovenpm viewYou can have a trynpm view @vue/cliAs you can seedist-tagsThere are two,latestandnextIf we don’t specify tag when publishing packages, we will publish them by defaultlatest

And, if we set the dependency version tolatestWhich means we install it every timelaetstThe latest version.

howevernextHow did it come about? We can do it herenpm publishWhen I was youngnpm publish --tag nextThat’s right. In this way, there will be one more tag for the sub release project.

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

NPM scripts hook

The hook of NPM can be divided into two types: pre and post. Pre means to execute before the instruction and post means to execute after the instruction.

There are several instructions in NPMstartstoptestrestartversioninstallpublishWhat does built-in instruction mean? That is, it can be passed directlynpm startInstead ofnpm run startIt’s not easy to carry out.


Take these out, because these instructions are almost the same, just add a pre or post in front. You can copy the following instructions to your computer 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 version can be set, butnpm run versionIt’s just a running command.

  "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 above in your mind. There are some special usages here. You can customize the instructions and add pre and post prefixes.

Of course, it can’t be used herenpm helloInstead of usingnpm run helloIt’s too late.

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


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

Let’s talk about it firstnpm installAs you can see below, exceptpreinstallandpostinstallIn addition, it has been implementedprepublishandprepareHowever, 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 seenpm publishThis is more useful. Let’s take a simple example,prepublishOnlyThis hook can be executed before publishing, such as project packaging or compilation, to prevent forgetting compilation and publishing directly.

In addition, after the release is successful, you can alsopostpublishTo upload package information to the 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, let’s distinguish between & & and | which belong to one group and belong to logical identifier, and | and & which belong to another group and belong to Linux function.

| &

Here, the front-end students may not know much about the first said, | is the pipeline, and a single & means to put the instructions into the background work.

#| pipeline
#Get test.txt  Document 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 should know some.

such asnpm run startAfter the service is started, it is directly hung on the terminal front desk.

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

I don't believe these NPM instructions. You know all about them

But if you runnpm run start &, end with & and start the service in the background. If you enterlsOr other instructions, you can see the console has output.

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

I don't believe these NPM instructions. You know all about them

Now that we’re here, let’s talk about a few more 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 learn about the following Linux instructions.

#Switch the background running or suspended service to the foreground running
#Running the pending service in the background
#It's also running the service in the background
#You can also query through jobs and stop with kill
#However, the log cannot be queried
#So in node, we usually use PM2 to suspend tasks
nohup npm run service &

Of course, in addition to starting the service and hanging it in the background, the instruction can be used for other purposes. For example, what you need to start is not the service, but just to run the instruction,npm run script1 & npm run script2 &These two instructions will run synchronously because they are both hung in the background.

|| &&

These two logic operators are familiar to us, || indicates that if the previous one runs incorrectly, for example, there is aprocess.exit(1);, before the next one is executed, & & indicates that the next one is executed only after the previous one runs successfully.

#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

NPX is what, NPX can understand the idiom sugar, behind the logic is the same, usually there are two main usages.

In the project package.json Used in

In the hypothetical project package.json As follows, when you want to executetscYou need to write in scripts when you are writing./node_modules/.bin/tsc --project ./

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

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

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

Ensure the execution of the latest script code

When NPX is used in creating a project, NPM will download the library to store temporary files and delete them after execution, which can ensure that the code is up-to-date every time it runs.

npx create-react-app my-react-appAre you familiar with it? We want to write their own library to run 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 how the library was originally used
    "my-cli": "bin/index.js",
    //Here is the code NPX actually runs
    //We just have to keep key and 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 global installation@scope/my-cliReexecutionmy-cli hello

Remove all modules installed globally

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

rm -rf /usr/local/lib/node_modules

Recommended by Haoku

Ranking regardless of order, will be recorded in accordance with the memory order of bloggers. Among them, there are command-line tools and easy-to-use three-party libraries. Most of them will not have three main frameworks of three-party libraries (you must know more than me), but will focus on node class libraries.

Yarn dependency processing tool

There are not too many things that are easy to use. Most people should use them. They can better deal with project dependencies by benchmarking NPM (but we also find that NPM can be installed successfully, and yarn will report an error instead).

Throw in the order, a word is to rush.

npm install yarn -g

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

Mirror config China Auto configure national image

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

This library will automatically configure the addresses of many third-party libraries (such as electronic) to the national image. Although it can also be manually configured when necessary, what’s more with one click operation! Download speed swish swish.

npm install -g mirror-config-china

NRM management registry

When you often need to switch registry sources (for example, you need tonpm publishCode, at this time 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’s very convenient to start a static service locally. Of course, there are many parameters. I don’t want to do more demonstration here. I just want to make a contribution. For details, you can see the following documents.


npm install -g http-server

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

cd dist

NVM manages multi version nodes

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


#View the currently used node version
nvm current
#Install the specified version of node
nvm install 12.14.0
#Switch node version
nvm use 12.14.0
#Running with node version 12.14.0 index.js
nvm run 12.14.0 index.js


Recently, the speed of hair loss is similar to that of lucky coffee, and the forgetfulness is getting bigger and bigger. I often forget what I was going to do just now with the code. I used to be able to keep four or five hours’ concentration on a thing, but now it’s easy to interrupt my thinking, thinking, ah, are you old? I’ve never had a panic about age before, but I look at the outstanding people in the company The new generation of China will inevitably have some anxiety. How to avoid anxiety? It’s not a work of forgetting to eat and sleep, but a work of making yourself an irreplaceable person. This is true of feelings and work.

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

PS1: after writing, I found that I didn’t know much about it. It was very miscellaneous. If you guys have private goods, you can share them with me secretly. I’ll figure out how to add them, crab.

PS2: it’s a bit of a headline party,I found that the amount of reading carefully written articles is less than that of interview articles, and my heart is unbalancedIf you know all about it, please add a group to ridicule me.


Code is life, I enjoy it.

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

I am here [email protected] Welcome to visit me.

You are welcome to join me and join the group to learn the front end. Remember to note where you saw my article from

I don't believe these NPM instructions. You know all about them

Recommended Today

How to Build a Cybersecurity Career

Original text:How to Build a Cybersecurity Career How to build the cause of network security Normative guidelines for building a successful career in the field of information security fromDaniel miesslerstayinformation safetyCreated / updated: December 17, 2019 I’ve been doing itinformation safety(now many people call it network security) it’s been about 20 years, and I’ve spent […]