preface
NPM as a front-end tool, it must be well mastered, in normal development, the most used should benpm install
However, 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 init
Create 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 publish
Publish 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
#Release
npm publish
npm view
View 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 root
Gets 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 root
The 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/.bin
There are two ways to find the directory
const moduleRootPath = path.join(process.cwd(), "node_modules");
const moduleRootPath = execa.sync("npm", ["root"]);
npm list
View globally installed modules
npm list -g --depth=0
npm cache
Clear NPM cache
report errorsnpm resource busy or locked
When 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 version
Quick 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-pre
There 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 prerelease
This 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 patch
nothing 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-size
Maybe 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;
cli.run();
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/hello
You can’t because you don’t have one@types
Permission 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.
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.
- If you just fix the bug, update it
patch
。 - If new features are added, but downward compatible, update them
minor
。 - If there is a big change, downward incompatibility, need to update
major
。
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、 <=1.1.0、1.1.x、1.1.*It’s quite special.
~1.1.0
~1.1.0
Can match to1.1.n
~1.1
Can match to1.1.n
~1
Can match to1.n.n
^1.1.0
Starting from the leftmost non-zero number in the version number, the number on the right can be any number.
^1.1.0
Can match to1.n.n
^0.1.0
Can match to0.1.n
latest
Latest is a special version number, which we mentioned abovenpm view
You can have a trynpm view @vue/cli
As you can seedist-tags
There are two,latest
andnext
If we don’t specify tag when publishing packages, we will publish them by defaultlatest
。
And, if we set the dependency version tolatest
Which means we install it every timelaetst
The latest version.
howevernext
How did it come about? We can do it herenpm publish
When I was youngnpm publish --tag next
That’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 NPMstart
、 stop
、 test
、 restart
、 version
、 install
、 publish
What does built-in instruction mean? That is, it can be passed directlynpm start
Instead ofnpm run start
It’s not easy to carry out.
start
、 stop
、 test
、 restart
、 version
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 start
、npm test
、npm stop
Wait, try.
It should be noted that,npm version
andnpm run version
It’s different,npm version
We mentioned earlier that version can be set, butnpm run version
It’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 hello
Instead of usingnpm run hello
It’s too late.
{
"prehello": "echo prehello",
"hello": "echo hello",
"posthello": "echo posthello"
}
install
、 publish
Let’s talk about two special instructions,npm install
andnpm publish
In addition to the prefixes of pre and post, there are several hidden hooks.
Let’s talk about it firstnpm install
As you can see below, exceptpreinstall
andpostinstall
In addition, it has been implementedprepublish
andprepare
However, 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 publish
This is more useful. Let’s take a simple example,prepublishOnly
This 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 alsopostpublish
To 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 start
After 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
l
Or other instructions, you can find that there is no output in the console.
But if you runnpm run start &
, end with & and start the service in the background. If you enterls
Or 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.
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
fg
#Running the pending service in the background
bg
#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 executetsc
You 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-app
Are 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-cli
Reexecutionmy-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 publish
Code, 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.
http-server
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-server
Service, he will default toindex.html
Start the static service as a portal and listen for file changes.
cd dist
http-server
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.
nvm
#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
Postscript
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.
footer
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