preface

NPM as a front-end tool, it must be well mastered, in peacetime development, the most used should be NPM install, but, such a powerful tool, the role must be more than that.

Now I sort out what I know about NPM, most of which I usually use a lot. The integration is not only convenient to find, but more importantly, as the successor of socialism, the good qualities of young Pioneers remind me to make due contributions to the society. Write this, I can not help but look down, the red scarf chest seems to be more red, the sun seems to smile and nod to me.

Again, before WE begin, the collection is constantly updated, because knowledge is always being added. But also will not update frequently, generally will save a big again put, continue to update, suggest collection, the article will be put in my blog anthology, blog inside or will update quickly.

For those of you who are Windows students, try cmder, the Windows command line wizard, which can reduce the number of strange errors that occur when using the Native Windows command line.

The command set

It is strongly recommended not to use CNPM, there are all kinds of strange bugs, setting Registry for NPM is a good choice compared to CNPM, using NRM is a better choice.

npm initCreate the base package.json

# this will be done interactively on the command line
npm init
# Skip the interactive and create package.json using defaultValue
npm init -y
Copy the code

npm publishRelease NPM package

Here is only a list of steps to publish, specific how to write the NPM package can be searched online related content, various big guy has sorted out a lot of, the blogger is not here to teach fish to swim.

It should be noted that we need to switch Registry to NPM origin first, but taobao cannot be used. Taobao is synchronized with the national resources of NPM package, and the actual resources are still from NPM. Therefore, it is necessary to publish to NPM first and then wait for Automatic synchronization of Taobao (which can brush a wave of downloads by the way).

Switch registry to NPM
nrm use npm

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

NPM publish for the first time
# login account, this step actually can not do, directly look at whoami
npm login

# Check current account
npm whoami
# release
npm publish
Copy the code

npm viewView details about a library

NPM install ${packageName}@${tag} NPM install ${packageName}@${tag}

npm view @vue/cli

After viewing the view, install the specified tag
npm install -D @vue/cli@next
Copy the code

npm rootGets the node_modules path of the current project

This can be used in the command line library, which looks up the path to node_modules and returns the absolute path.

But there is a bug, if you use NPM root in an empty folder, it will return the current path with node_modules, even if there is no node_modules folder in your directory.

npm root
Copy the code

For example, if you’re in a deep path and need to use the node_modules/.bin directive that your current project depends on, there are two ways to find the directory

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

npm listView globally installed modules

npm list -g --depth=0
Copy the code

npm cacheClear the NPM cache

Try NPM resource busy or locked when an error is reported.

# force the table forcibly clears the cache
npm cache clean --force
Copy the code

npm versionQuickly change project versions

How to change the project version number correctly? Is manual modification a little low? Here is how to change the correct version number.

We mentioned above the version rules of NPM, here we will mention major.minor.patch-pre again, we will refer to it as temporary version, not mentioned above because temporary version is rarely used.

Get the dependent version of the current project
npm version

# Change the current project version to 1.1.5NPM version 1.1.5Copy the code

Note that NPM Version prerelease is the command to change the incremental temporary version.

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

Update temporary version 1.1.5 -> 2.0.0-0 for major version
npm version premajor
# Temporary version 1.1.5 -> 1.2.0-0
npm version preminor
Update temporary patch version 1.1.5 -> 1.1.6-0
npm version prepatch

# NPM version pre* (NPM version pre*)
# No, all pre* temporary versions are incremented by the following command
npm version prerelease
Copy the code

By the way, yarn can also be changed with the command, but you need to use YARN Version –new-version patch.

Node runs out of memory

Use –max-old-space-size to solve this problem.

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

Of course, if you have a lot of commands in package.json scripts, you’ll need to add them everywhere, there has been an issue about this, and maybe a later version of Node will fix this.

Add max-old-space-size to npmrc

Again, we can add not only scripts, but also execution commands, such as the following, in the bin directory of a command line library.

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

const cli = require(".. /src").default;
cli.run();
Copy the code

What is NPM scope @?

Dependencies are prefixed with @? This is the scope mechanism of NPM, which can be understood as organization, such as @types/node and @vue/cli. The @ before is organization, and only the package manager can upload the package to the corresponding scope. You can’t post @types/hello if you want because you don’t have access to @types.

So how do you publish projects with @ prefixes? You must first apply for the corresponding @${scope} in the NPM management interface, as shown below.

NPM version number description

First, the version number rule of NPM is major.minor.patch, which means major version, minor version, and patch version. When releasing, we need to follow the following principles.

  1. Update if it’s just a bug fixpatch.
  2. Update if new functionality is added but backward compatibleminor.
  3. If there are major changes, downward incompatible, need to updatemajor.

1.1.0, >1.1.0, >=1.1.0, <1.1.0, <=1.1.0, 1.1.x, 1.1.*

~ 1.1.0

The value ranges from 1.1.0 to 1.1.n

~1.1 can be matched to 1.1.n

The value of ~1 can match 1.n.n

^ 1.1.0

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

^1.1.0 can match 1.n.n

^0.1.0 can match to 0.1.n

latest

“Latest” is a special version number, we mentioned NPM view, you can try NPM view@vue /cli, you can see that there are two dist-tags, “latest” and “next”. If we don’t specify tag when we publish the package, The default is “latest”.

Also, if we set the dependency version to Latest, this means that we will install the latest version of Laetst every time.

But how did next come about? We can publish with NPM publish –tag next and publish with an extra tag.

During installation, unless NPM install@vue /cli@next is specified, you will not fall under this tag.

NPM scripts hook Script hook

NPM hooks can be simply divided into two types: Pre and POST. Pre stands for execution before instruction, and POST stands for execution after instruction.

NPM built-in commands include start, stop, test, restart, version, install, publish. This can be done directly via NPM start instead of NPM run start.

start,stop,test,restart,version

You can copy the following commands into your package.json file and run the corresponding NPM start, NPM test, NPM stop, etc.

Note that NPM version is not the same as NPM run version. As mentioned earlier, NPM version can be set, while NPM run version is simply run 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"
}
Copy the code

There are also special uses for customizing commands and adding pre and POST prefixes.

Of course, instead of using NPM Hello, you use NPM run Hello.

{
  "prehello": "echo prehello"."hello": "echo hello"."posthello": "echo posthello"
}
Copy the code

install,publish

Two more special directives, NPM install and NPM publish, have several hidden hooks in addition to the pre and POST prefixes.

Check for NPM install, below you can see in addition to preinstall and postinstall also perform prepublish and prepare, but here only the hooks are given, respectively played an actual application scenario.

{
  "preinstall": "echo preinstall"."install": "echo install"."postinstall": "echo postinstall"."prepublish": "echo prepublish"."prepare": "echo prepare"
}
Copy the code

NPM publish hook: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly: prepublishOnly

Postpublish can also be used to upload package information to the database after a successful publication.

{
  "prepublish": "echo prepublish"."prepare": "echo prepare"."prepublishOnly": "echo prepublishOnly"."prepack": "echo prepack"."postpack": "echo postpack".// Will not be executed until successful publication
  "postpublish": "echo postpublish"
}
Copy the code

NPM scripts &, &&, | | |

To differentiate the first, && and | | is a group of, belongs to the logical identifier, and | and & is another mob, belong to the function of the Linux.

| &

Here the front students may not understand say first, | is pipeline, while a single & said will work instruction in the background.

# | pipe
Get the contents of the test.txt file
# And pass the content to less for easy browsing
# less is a Linux directive to browse files at will
cat test.txt | less
Copy the code

The following command may not be familiar to the front end, but to the server side.

For example, NPM run start, after the service is started, it is directly hung in the terminal foreground.

What do you mean it’s on the front desk? After the service is started, we can try to type ls L or some other command and find no output in the console.

But if you run NPM run start &, ending with &, to start the service in the background, if you type ls or some other command at this point, you can see the console output.

Never mind the previous output, that is the vue-cli-service output, which is directly printed to the screen.

While we’re at it, let’s talk about a few common Linux commands.

# Hang the service in the background
npm run service &
# View the services hanging in the background
# will return a service with an ID, as follows
# [1] + 1967 running npm run service
jobs -l
# kill the service running in the background
kill 1967
Copy the code

For those of you who are interested, check out the Linux instructions below.

Switch background running or pending services to foreground running
fg
Run the suspended service in the background
bg
Run the service in the background
# Can also be queried by jobs and stopped by kill
The log cannot be queried
So normally in Node, we use pm2 to suspend tasks
nohup npm run service &
Copy the code

Hang in the background of course, in addition to start the service instruction, he has other USES, such as you don’t need to start the service, just want to run the instruction, NPM run script1 & NPM run script2 &, these two instructions will be synchronous operation, because they were on the background.

| | &&

Both is our familiar with logical operators, | | said before if a run-time error, such as the code in the process, the exit (1); And && indicates that the next operation is executed only when the previous operation succeeds.

Execute test, log if an error is thrown
npm run test || npm run loginfo
Execute install and then start
npm run install && npm run start
Copy the code

What is NPX? I want to use my own library, too

NPX is a syntactic sugar. It has the same logic behind it.

Used in the project package.json

If your project package.json looks like this, you need to write./node_modules/.bin/ TSC –project./ in scripts when you want to execute TSC.

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

But using NPX you can omit node_modules/.bin/ as follows.

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

Ensure that the latest script code is executed

When using NPX in your project, NPM downloads the library to store temporary files and deletes them upon execution, ensuring that the code is up to date every time it is run.

NPX create-react-app my-react-app It is also easy to run the library we have written in NPX by configuring it in package.json 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 that NPX actually runs
    // We just need to keep the key the same as packPage.name
    "@scope/my-cli": "bin/index.js"}}Copy the code

Next, publish your library and use NPX @scope/my-cli Hello, which is equivalent to installing @scope/my-cli and then executing my-cli Hello.

Delete all modules installed globally

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

rm -rf /usr/local/lib/node_modules
Copy the code

Good library recommendation

The list is not in any particular order, but in the order the blogger remembers it. There is a command line tool, and a nice tripartite library recommendation. There will probably be no tripartite library of the major three frameworks (you know more than I do), and the Node library will be the main class library.

Yarn dependency processing tool

NPM can handle project dependencies better. (However, it is also found that there are cases where NPM can be successfully installed and YARN installation can report an error.)

Throw in the order. It’s a word for it.

npm install yarn -g

Install devDEp dependencies
yarn add -D @types/node
Install deP dependencies
yarn add axios
# Install peerDep dependency
# peerDep if you install me, you should also install XXX
yarn add -P vue
# Global install dependencies
yarn global add @vue/cli
Copy the code

Mirror-config-china Automatically configures country mirroring

When downloading some libraries, find that even when Registry is configured, the download is still extremely slow, or even half a day? You might need this.

This library will automatically configure many third-party libraries (such as electron) address to the country mirror, although it can also be manually configured when needed, but, there is a button operation that also what bicycle! Download speeds swish.

npm install -g mirror-config-china
Copy the code

NRM management registry

This tool can help when you frequently need to switch to the Registry source (for example, if you need NPM publish code, you need to switch to the NPM source).

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
# Use registry for Taobao
nrm use taobao
# Use registry for NPM
nrm use npm
Copy the code

HTTP -server starts static services soon

Can be very convenient in the local up a static service, of course, there are a lot of parameters, here is not much to do a demonstration, just do a piece of advice, you can view the following documents.

http-server

npm install -g http-server
Copy the code

As a small example, when you’ve happily developed a project and packaged it into Dist to see how it looks, you can go to the dist folder and start the HTTP-Server service, which starts the static service with index.html as the default entry and listens for file changes.

cd dist
http-server
Copy the code

NVM manages multiple versions of Nodes

While it may be rare, you’ll still run into the problem of running different versions of Node on the same computer, which this library solves.

nvm

Check the current node version
nvm current
Install the specified version of NodeNVM install 12.14.0Switch node versionsNVM use 12.14.0Run index.js with node 12.14.0NVM run 12.14.0 index. JsCopy the code

After the language

Recent hair loss rate and rui xing coffee drop speed, forgetfulness is becoming more and more big, often code forgot I write this just what I need to do, for one thing that can keep the four or five hours before focus, now thinking is very easy to interrupt, thinking, oh is old, had never panic about age, But looking at the company’s best young generation, it can be a little unsettling. How can ability not anxious? Not work, but should let oneself become irreplaceable that person, love is so, work is so.

Here is not a hot spot, the great news of Stuart Zhengmei must be known more or less, regrettably, it is said that the fall of genius is not too much. Therefore, in the usual development and learning, in addition to paying attention to technical details, we should pay more attention to our own body. There are many opportunities to make money, but only a healthy body can support your great ideals.

Ps1: after I finished writing, I found that I didn’t know much about it. It was quite miscellaneous. If you have some private goods, you can share them with me secretly.

Ps2: a bit of the title party, found carefully written articles read than the interview article (refers to some), the heart is not balanced, if you know all, please add group to group ridicule me.

The footer

Code is life, and I love it.

Technology is constantly changing. Brains are always online. We’ll see you next time

By — Crotch Trio

I am here gayhub@jsjzh welcome to find me to play.

Welcome friends to join me directly, pull you into the group to do things, remember to note where you read the article.

Ps: If the picture is invalid, you can add my wechat: Kimimi_king