Initialize the

Before using NPM, you need to initialize the current directory:

npm init
Copy the code

We can run NPM init -h to learn more about init parameters:

% npm init -h
npm init

Usage:
npm init [--force|-f|--yes|-y|--scope]
npm init <@scope> (same as `npx <@scope>/create`)
npm init [<@scope>/]<name> (same as `npx [<@scope>/]create-<name>`)

aliases: create, innit

Run "npm help init" for more info
Copy the code

NPM help Init can be read in more detail.

When you run NPM Init directly, you will be prompted step by step for the developer to enter the appropriate information. The familiar package.json file is then generated in the current directory.

If you don’t want to bother, you can skip the input step by simply NPM init -y.

It is recommended to initialize the directory with Git before NPM initialization. The advantage of this is that the REPO entry will be automatically populated with git origin during NPM init.

Git remote add origin git://Copy the code

To sum up:

  • In the use ofnpmBefore, should be usednpm initInitialize and create a directorypackage.jsonFile.
  • usenpm init -yTo skip the initialization interaction.
  • Suggest proceeding firstgit initAnd configure itoriginThe source.

Package management

Source configuration

View current source Settings

npm config get registry
Copy the code

Configuring a New Source

npm config set registry https://registry.npm.taobao.org
Copy the code

Specified source installation

npm --registry https://registry.npm.taobao.org install <package-name>
Copy the code

In addition, the distribution source defaults to the installation source. I have the impression that the distribution source can be configured separately, but it is not very useful.

Install the NPM package

npm install <package-name>
Copy the code

Or you could write it as

npm i <package-name>
Copy the code

Install multiple packages at the same time

npm i <package1> <package2> <package3> ...
Copy the code

Depend on the level

Packages have two dependency levels: project dependency and development dependency.

Project dependency means that the package is needed to run the current project release, so it should be pushed into the final package when packaged using something like WebPack. React redux antD or something like that. This type of package is marked with the Dependencies field in package.json.

The packages in the development dependency, the current project should not run dependencies on them, are generally around the project compilation, packaging, integration and other auxiliary work peripheral tools. Such as WebPack and various Babel plug-ins. This type of package marks the devDependencies field in package.json.

Of course, during project packaging, the packaging tool will do treeshake actions to shake off unused packages, but maintaining a strict package dependency should be a priority for the front end when managing the project, and Treeshake is also limited.

Install project dependencies
npm install <package-name>
npm install <package-name> --save
npm install <package-name> -S
Copy the code
Install development dependencies
npm install <package-name> --save-dev
npm install <package-name> -D
Copy the code

A real package.json code:

{..."dependencies": {
    "@babel/core": "^ 7.14.6"."@babel/plugin-transform-react-jsx": "^ 7.14.5"."chalk": "^" 2.4.2."commander": "^ 7.2.0"."md5": "^ 2.3.0." "."watch": "^ 1.0.2"
  },
  "devDependencies": {
    "@types/babel__core": "^ 7.1.14"."@types/md5": "^ 2.3.0." "."@types/watch": "^" 1.0.1."ts-node": "^ 10.0.0"."typescript": "^ 4.3.4." "}}Copy the code

Uninstall packages

# Unload project dependencies
npm uninstall -S <package-name>
# Uninstall development dependencies
npm uninstall -D <package-name>
Uninstall global package
npm uninstall -g <package-name>
Copy the code

Global package

Like tools like webpack-cli or create-react-app, these packages can be treated as a tool to run directly from the bash command when NPM installs them globally.

Install the global package
npm install -g <package-name>
Uninstall global package
npm uninstall -g <package-name>
Copy the code

There are a few things to note about installing the global package:

  1. Is the installation location configured in the environment variable? Otherwise, it cannot be executed.

  2. Some tools like NVM will install the -g package by node version. After switching node version, the package may not be found, or problem 1 May occur.

  3. On the Mac operating system, sudo is required for uninstall and -g installation if DMG is downloaded from the official website. Homebrew is recommended for node installation.

  4. Tools such as Webpack TS-Node TSC can be installed as a development dependency of the project and run through NPM rather than -g. The advantage of this is that the project is decoupled from the development environment. Here is an example of configuring the TS compiler in a development dependency and compiling ts files in scripts.build:

    {
      "scripts": {
        "build": "tsc ./src/*.ts --esModuleInterop -d -t ES5 --lib es5 --outDir dist"
      },
      "devDependencies": {
        "typescript": "^ 4.3.4." "}}Copy the code

package-lock.json

Used to lock the version number of the installation package.

This file may cause some problems, such as the locked lower version being taken offline from the NPM source.

So when I don’t have a strong version requirement, or I trust the package author, I usually put this file in.gitignore. The version that needs to be locked is written directly to package.json.

About version Number

The ^ character in the version number will not jump to a larger version after testing.

For example, NPM I webpack@^3 will only install the latest version of WebPack 3, not WebPack 4 or even WebPack 5.

If you want to install the latest version, use @latest version

npm i <package-name>@latest
Copy the code

Write instruction script

Instruction + bash

In the scripts of package.json, configure the NPM directive and the corresponding run script.

There is a default test directive:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
}
Copy the code

We can try:

% npm run test

> [email protected] test
> echo "Error: no test specified" && exit 1

Error: no test specified
npm ERR! code 1
npm ERR! path /Users/kema/testnpm
npm ERR! command failed
npm ERR! command sh -c echo "Error: no test specified" && exit 1
Copy the code

In fact, it is executed in bash

echo "Error: no test specified" && exit 1
Copy the code

Where && connects the two bash commands echo and exit sequentially.

Note the final exit 1, which triggers the NPM ERR! Code 1 a series of error stacks.

Let’s change it:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 0"
}
Copy the code

NPM returns no error after changing to exit 0:

% npm run test    

> [email protected] test
> echo "Error: no test specified" && exit 0

Error: no test specified
Copy the code

So NPM run is just running the bash command.

Instruction + node

Let’s write a build.js file:

console.log('build')
Copy the code

Add the build directive to scripts:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 0"."build": "node build.js"
}
Copy the code
% npm run build   

> [email protected] build
> node build.js

build
Copy the code

This way, we write whatever code we want in build.js and then use NPM to execute it. Our NPM run build command remains the same whether the business logic of build.js is changed or the JS file is replaced directly in scripts.build. This has important implications for integration, operations, and so on.

Front and rear command: pre | post

Take the build directive for example,

  • prebuildTo run onbuildbefore
  • postbuildTo run onbuildafter

We make the following changes to scripts:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 0"."build": "node build.js"."prebuild": "echo \"Starting... \ ""."postbuild": "echo \"Done! \ ""
}
Copy the code
% npm run build   

> [email protected] prebuild
> echo "Starting..."

Starting...

> [email protected] build
> node build.js

build

> [email protected] postbuild
> echo "Done!"

Done!
Copy the code

As you can see, prebuild build postbuild is executed in sequence.

NPM workflow

We can construct a workflow using pre/ POST directive features:

"scripts": {
    "pretest": "echo \"preparing for testing... \ ""."test": "echo \"testing... \" && exit 0"."posttest": "test done!"."build": "node build.js"."prebuild": "npm run test"."postbuild": "echo \"Done! \ ""
}
Copy the code
% npm run build   

> [email protected] prebuild
> npm run test


> [email protected] pretest
> echo "preparing for testing..."

preparing for testing...

> [email protected] test
> echo "testing..." && exit 0

testing...

> [email protected] posttest
> test done!


> [email protected] build
> node build.js

build

> [email protected] postbuild
> echo "Done!"

Done!
Copy the code

The above process is as follows:

  1. npm run build
  2. prebuildCommand to runnpm run test
  3. pretestCommand to run
  4. testCommand to run
  5. posttestCommand run, at this pointprebuildInstruction completed.
  6. buildCommand to run
  7. postbuildCommand to run

Let’s make a bit of an instruction error and see how the workflow works:

"test": "echo \"testing... \" && exit 1"
Copy the code

We have the test instruction exit 1, which causes the test instruction to report an error, simulating the termination of the build workflow if the unit test fails.

% npm run build   

> [email protected] prebuild
> npm run test


> [email protected] pretest
> echo "preparing for testing..."

preparing for testing...

> [email protected] test
> echo "testing..." && exit 1

testing...
npm ERR! code 1
Copy the code

As you can see, when the test directive is run, the workflow interrupts and exits, as expected.