preface

In Node.js, a module is a library or framework as well as a Node.js project. The Node.js project follows a modular architecture. When we create a Node.js project, we create a module, and the module’s description file is called package.json.

I’ve seen the package.json file scripts in other projects write this:

"dev": "rimraf \"config/.conf.json\" && rimraf \"src/next.config.js\" && cpx \".conf.json\" \"config/\" && nodemon server/index.ts"."clean": "rimraf ./dist && mkdir dist"."prebuild": "npm run clean"."build": "cross-env NODE_ENV=production webpack"
Copy the code

At that time, I was a little confused, so I made up the relevant knowledge, and found that there are many places in the original package.json that we ignored. If youdao friend and I are a little confused, this article can not be missed.

bin

It is a mapping between a command name and a local file name. On install, NPM will link these files to prefix/bin using symbolic links if it is a global installation and to./node_modules/.bin/ if it is a local installation.

The common understanding is that if we install globally, we can execute the file on the command line, and if we install locally, we can execute the file on the command line in the current project directory.

"bin": {
    "gynpm": "./bin/index.js"
}
Copy the code

Note: the index.js file must have the #! Header. /usr/bin/env node, otherwise the script will start without the node executable.

Small experiment

Create a package.json file with NPM init -y.

{
    "name": "cc"."version": "1.0.0"."description": ""."main": "index.js"."bin": {
        "mason": "./index.js"
    },
    "scripts": {},
    "keywords": []."author": ""."license": "ISC"."dependencies": {}}Copy the code

Create an index.js file in the same directory as package.json

#! /usr/bin/env node

console.log('cool')
Copy the code

Then run the following command in the project directory: sudo npmi-g in the MAC directory and npmi-g in the window directory

Next you open a new command line in any directory, type Mason, and you’ll see

Cool field.

I don’t know if this little experiment will give you a better understanding of what this bin does. Examples such as vue-cli, create-React-app and so on all map commands to the global via the bin attribute.

main

Main is important because it is the main entry point for our project.

"main": "app.js"
Copy the code

As such, our project will use the app.js file in the root directory as our project entry file.

scripts

NPM allows you to define script commands using the scripts field in package.json files. Advantages: The scripts associated with the project can be centralized in one place.

Different project script commands, as long as the same function, can have the same external interface. Users don't need to know how to test your project, they just need to run NPM Run test. You can take advantage of many of the accessibility features that NPM provides.Copy the code

The principle of the NPM script is very simple. Whenever NPM run is executed, a new Shell is automatically created in which the specified script command is executed. Therefore, any command that a Shell (typically Bash) can run can be written in an NPM script.

In particular, the new Shell created by NPM run will add the node_modules/.bin subdirectory of the current directory to the PATH variable, and then restore the PATH variable after the execution.

This means that all scripts in the node_modules/.bin subdirectory of the current directory can be called directly by the script name without adding a path. For example, if the current project has Mocha in its dependencies, just write Mocha Test directly.

* wildcard

* indicates any file name, and ** indicates any level of subdirectories.


"lint": "jshint *.js"
"lint": "jshint **/*.js"

Copy the code

If you pass a wildcard into the original command to prevent it from being escaped by the Shell, escape the asterisk.

"test": "tap test/\*.js"
Copy the code

Script passthrough symbol: —

"server": "webpack-dev-server --mode=development --open --iframe=true ".Copy the code

Script execution sequence

For parallel execution (that is, parallel execution at the same time), the ampersand symbol can be used

$ npm run script1.js & npm run script2.js
Copy the code

For secondary execution (that is, the next task is executed only if the previous task succeeds), the && symbol can be used

$ npm run script1.js && npm run script2.js
Copy the code

The script hook

The NPM script has two hooks, pre and POST, in which you can do some preparation and cleanup

eg:

"clean": "rimraf ./dist && mkdir dist"."prebuild": "npm run clean"."build": "cross-env NODE_ENV=production webpack"
Copy the code

NPM provides the following hooks by default:

Prepublish, postpublish preinstall, postinstall preuninstall, postuninstall preversion, postVersion Pretest, Posttest prestop, postStop prestart, poststart prerestart, postrestartCopy the code

Get the variable of package.json

A very powerful feature of the NPM script is the ability to use the internal variables of NPM.

First, with the npm_package_ prefix, the NPM script gets the fields in package.json. For example, here is a package.json.

// package.json
{
  "name": "foo"."version": "1.2.5"."scripts": {
    "view": "node view.js"}}Copy the code

We can do this in our js:

console.log(process.env.npm_package_name); // foo
console.log(process.env.npm_package_version); / / 1.2.5
Copy the code

Commonly used script


// Delete the directory
"clean": "rimraf dist/*".// Set up an HTTP service locally
"serve": "http-server -p 9090 dist/".// Open the browser
"open:dev": "opener http://localhost:9090".// Refresh in real-time
 "livereload": "live-reload --port 9091 dist/".// Build the HTML file
"build:html": "jade index.jade > dist/index.html".// Redo the build whenever the CSS file changes
"watch:css": "watch 'npm run build:css' assets/styles/".// Re-execute the build whenever the HTML file changes
"watch:html": "watch 'npm run build:html' assets/html".// Deploy to Amazon S3
"deploy:prod": "s3-cli sync ./dist/ s3://example-com/prod-site/"./ / build the favicon
"build:favicon": "node scripts/favicon.js".Copy the code

Introduces several useful modules in NPM scripts

CPX global replication

A useful module to monitor global file changes and copy them to the desired directory

We can use the NPM installation in the NPM script:

"copy": "cpx \".conf.json\" \"config/\" "
Copy the code

You can run NPM run copy to copy the.conf.json file from the root directory to the config folder. If there is no config folder, you will create a new one.

cpx "src/**/*.{html,png,jpg}" app --watch
Copy the code

When any. HTML,. PNG,. JPG files in the SRC directory change, copy them to the app directory.

Cross-env can set and use environment variables across platforms

For the most part, using the Windows platform is similar to: The NODE_ENV=production command line command gets stuck. There are many differences between Windows and POSIX when using the command line (for example, $ENV_VAR on POSIX, %ENV_VAR%…).

Cross-env makes this easy, using unique instructions for different platforms without worrying about cross-platform issues:

"start": "cross-env NODE_ENV=production node server/index.js".Copy the code

Dependencies and devDependencies

These are the main places to store the libraries that your project depends on. DevDependencies are for local development, but they are brought online while you are developing.

NPM I XXX -s is placed in dependencies, NPM I XXX -d is placed in devDependencies. So when you load the package, you must consider whether the package can be used online. Don’t put it all in dependencies to increase the size and efficiency of the package.

peerDependencies

We see this attribute in package.json for some projects. It is mainly for compatibility purposes. In common sense, we can use this attribute to tell people who want to use our module:

If you want to use me, you’d better take xxX1 and XXX2, or I might get you into trouble.

"peerDependencies": {
        "xxx1": "1.0.0"."xxx2": "1.0.0",}Copy the code

In this way, when you pack your bags, you also carry the xxX1 and XXX2 bags.

Personally, these are the most important ones. Others, such as author, version, keywords, and description, are easy to understand.

reference

npmjs

Ruan Yifeng blog