npm package.json

When ‘NPM init’ is executed, the ‘package.json’ file is generated, which can be interpreted as a list of projects. It can help us list the packages that the project depends on, specify which package versions the project can use, and so on

structure

The JSON format must be followed; otherwise, it cannot be read by programs that try to programmatically access its properties

Common Field Description
'version'-- indicates the current version.'name'-- Set the name of the application/package.'description'-- is a short description of the application/package.'main'-- Sets the entry point for the application.'private'-- If set totrueCan prevent applications/packages from being accidentally published to NPM.'scripts'Defines a set of Node scripts that can be run.'dependencies'-- Sets a list of NPM packages installed as dependencies.'devDependencies'-- Sets a list of NPM packages installed as development dependencies.'engines'Set which version of Node.js this package/application will run on.'browserslist'-- Used to tell which browsers (and their versions) to support.Copy the code

version

1.Package version management Various version symbols Version Exact match version > Version must be greater than a certain version >= Version greater than or equal to <version less than <= versionVersion Less than ~version"Approximately equal":  
^version "Compatible version": version1, version2 equivalent > = version1 < = version2. Range1 | | range2 range1And scope2Either one will doCopy the code
About the version
1.NPM adopts the Semver specification as a dependency versioning scheme. According to Semver's convention, the version format of an NPM dependency package is generally:'Major version number. Minor version number. Revision Number (X.Y.Z) '- Tip js has a special validation'semver'1.1.'Major version number (also called major version)': A major release change is likely to be a disruptive change, which means there may be an API or usage that is incompatible with the minor release (e.g., vue)2 -> 3).1.2.'Minor version number (also called minor version)': Changes to minor releases should be compatible with apis and usages in the same major release, and therefore should be insensitive to developers. So we usually just say the big version number, and rarely get down to the small version number.1.3'Revision number (also called patch)': generally used to fix bugs or minor changes, but also to maintain forward compatibility'attention': If the larger version number is0This means that the software is in the initial stage of development, everything can change at any time, and there may be incompatibilities between minor versions. So when choosing dependencies, try to avoid large version numbers0The package.1.4.'Prior version'You may want to release an advance version when a release is large, unstable, and may not meet the expected compatibility requirements. The prior version number can be added to the major version number. Second version number. Revision number is followed by a join number followed by a series of identifiers separated by periods and version compilation information.'Internal (alpha), public (beta), official Release candidate RC: Release candiate'Alpha: Preview, or internal beta; Generally not to external release, there will be a lot of bugs; Generally only used by testers. Beta: beta, or public beta; This phase of the release will always add new features; It will be released after alpha. Rc (release candidate) : final test version; A potential release candidate for the final product, or for release if there are no problems.2.'Simple summary'Semver as a package versioning specification. This specification specifies that a software release consists of three parts:2.1Major incompatible major changes have been made to the major version number2.2. The second version has been added with backward compatible functionality2.3. Patch version number has been bug fixed for backward compatibilityCopy the code
  • Vue3 version is available

For each symbol meaning
1.~: if a new version is obtained during dependency installation, install the latest version of z in X.Y.Z. That is, keep the latest version of the revision number without changing the major and minor versions.2.^: When a new version is obtained during the installation dependency, y and Z are the latest versions installed in X.Y.Z. That is, keep the minor version number and revised version number as the latest version while keeping the main version number unchanged.3.The '*'"x"Or (empty) indicates that any version can be matched. Note:'When the major version number is 0, it is considered to be an unstable version'Both major and minor versions are0: ^0.0Z, ~0.0Z are treated as fixed versions and do not change when installing dependencies. The major version number is0: ^0.Y.z is the same as ~0.The same as y.z. Only the revision number is the latest version.Copy the code
Just a couple of examples
1."signale": "1.4.0": Fixed version number2."figlet": "*": Any version (>=0.0. 0)3."react": "16.x": Matches major versions (>=16.0. 0 <17.0. 0)4."react": "16.3.x": Matches major and minor versions (>=16.3. 0 <16.4. 0)5."^xxx": leftmost non0The version number cannot be smaller than XXX ^1.23.= > =1.23. <2.0. 0The main version number remains the same as ^0.12.= > =0.12. <0.2. 0The major and minor versions remain ^0.02. = = 0.02.The major, minor, and patch versions remain unchanged6."~xxx": If the minor version number is listed, the minor version number does not change. If the minor version number is not listed, the major version number does not change. The major version number cannot be smaller than XXX ~1.23.= > =1.23. <1.3. 0The major and minor versions remain ~1= > =1.0. 0 <2.0. 0The major version number remains unchangedCopy the code
Pre-release version
1.Think of it as a package developer: assume that the current online version is"1.2.3"If I make some changes and need to release the version"1."But I don't want to go directly online (because of the use"~ 1.2.3"or^ "1.2.3"), which requires the use of pre-publish functionality. So I might publish"1 - alpha. 1"or"1 - beta. 1"And so on.1 "> 1 - alpha."Said to accept"1 - alpha"Version under all greater than1Pre-release version of. so"1 - alpha. 7"I mean, it fits the bill, but"1 - beta. 1""1.2.5 - alpha. 2"None of them. In addition, if the version is official (without pre-release keywords), as long as the version number meets the requirements, do not check the pre-release version number, for example"1.2.5"."1.3.0"It's all recognized."~1.2.4-alpha.1"said"> = 1 - alpha. 1 < 1.3.0". such"1.2.5"."1 - alpha. 2"All fit the bill, and1.2.5 - alpha. "1"."1.3.0"Do not meet.1 "" ^ 1 - alpha.said"> = 1 - alpha. 1 < 2.0.0." ". such"1.2.5"."1 - alpha. 2"."1.3.0"Meet the requirements, and1.2.5 - alpha. "1"."2.0.0"Do not meet.Copy the code
I want to know more about semver semantics

Semver semantic version 2.0.0

The little knowledge
1. 1.0. 0Is used to define the public API. When your software is released to a formal environment or has a stable API, you can release it1.0. 0The version. So, when you decide to release an official version of the NPM package externally, mark its version as1.0. 0.Copy the code

Common field

About ‘mian’, ‘script’

Main — The main entry file

1.The value of the main configuration item is the path to a JS file that will be used as the main entry file for the program. That is, when someone else uses the bagimport testNpm from 'testNpm'TestNpm /index.js fileexportModule out. You can also import files yourselfCopy the code
Let’s look at the packet-finding mechanism
  • When specifying a specific path
require('./find.js');
require('./find');
1.requireMethod Find the module according to the module path, if it is a full path, directly import the module.1.1.module suffix omitted, first find JS files with the same name and then find JS folder with the same name1.2Index.js = index.js = index.js = index.js = index.js = index.js1.3If there is no index.js in the package.json file in the current folder, it will look for the entry file in the main option (the path can also be specified to node_modules), so looking for package.json is also the case1.4An error is reported if the specified entry file does not exist or the specified entry file is not foundCopy the code
  • No specific path is specified
require('find');
1.Node.js assumes it is a system module, and node.js goes to the node_modules folder1.1First check if there is a JS file with that name1.2. Then see if there is a folder with that name1.3If it is a folder, see if there is index.js in it1.4If there is no index.js look at the main option in package.json in that folder to determine the module entry file or you will not find an errorCopy the code
Good article

Json you are not aware of the browser, module, main fields priority – SegmentFault think no

Bin Specifies the script

Many modules have one or more executable modules that need to be configured to the PATH PATH. NPM makes this easy (in fact, NPM itself is also installed as an executable via the bin property). If you want to use this functionality of NPM, configure one in package.json'bin'Properties. The bin attribute is a map whose command name is key and local file name is value as follows:Copy the code
{ "bin" : { "myapp" : "./cli.js"}}Copy the code
If the module is installed globally, then'npm'for'bin'In the bin directory to create a soft connection (for Windows, the default is'C:\\Users\\username\\AppData\\Roaming\\npm'/node\_modules/.bin/ in the project./node\_modules/.bin/. So click on the example above when you install'myapp'NPM will be in for cli.js'/usr/local/bin/myapp'Path creates a soft link. If your module has only one executable and its command name is the same as the module name, you can simply write a string instead of the above configuration, for example:Copy the code
{ "name": "my-program"
, "version": "1.2.5"
, "bin": "./path/to/program" }
Copy the code

The effect is the same as the following:

{ "name": "my-program"
, "version": "1.2.5"
, "bin" : { "my-program" : "./path/to/program"}}Copy the code
What is soft connection
1.A soft link (symbolic link) is a special type of executable that contains a reference to another file or directory in the form of an absolute or relative pathCopy the code
For example
1.'cli-service'The package.json bin tells the CLI where to execute the script, in'node_moduels/.bin'The next thing to do is in the project'./node\_modules/.bin/'Directory to create a soft link.Copy the code

  • node_moduels/.bin

Scripts — sets of instructions

1.use'scripts'Field defines a script command that runs a script instruction'npm run  [--silent] [-- 
      
       ...] '
      In fact, the instructions above are'npm run-script  [--silent] [-- 
      
       ...] '
      Abbreviations, such as vuecli, are common'scripts'Configuration instructions:"scripts": {
  "serve": "vue-cli-service serve". } How does the script executeCopy the code
View the current list of all executable scripts
1. npm run
Copy the code
The working principle of
1.It's essentially executing'Commands that a Shell (usually Bash) can run'Shell is platform dependent. By default, the UNIX-like operating system is'/bin/sh'Instruction, Windows operating system is'cmd.exe'. The actual is'/bin/sh'The referenced shell is also platform dependent.'[email protected]'You can use'script-shell'Customize your shell configuration.Copy the code

Script types can be run

1.Check the perform'shell'Script location usage instructions'npm config get shell', the output result of my local configuration environment is'C:\Windows\system32\cmd.exe'In fact, it is'window'Of the system'cmd'Command line tools.Copy the code
The first kind of built-in instruction
1.In Win actually runs on'cmd'So the internal commands of the system CMD, without the need to install additional plug-ins, can be executed directly, in'npm'the'scripts'For example:"scripts": {/* System command */
      "ip":"ipconfig"
 }
Copy the code
The second carries out external commands
1.If we install node,git and other clients, we can directly execute in CMD window (need to configure the system environment variables). For example, after installing Node, we can directly input in console'node -v'To view node version information, you can also perform the following example"scripts": {/* Global external command */
    "git":"git --version"."node":"node -v",}Copy the code
The third way is to execute the project internally
1.When we install similar'vuecli'or'webpack'.'eslint'For internal use in these projects, each time NPM run is executed, a new Shell is automatically created, which puts the current project's'node_modules/.bin'Is added to the environment variable PATH. After the command is executed, the environment variable PATH is restored to its original state. Can be interpreted as a pre-directory'node_modules/.bin'All scripts in subdirectories can be called directly with the script name, without adding a path. For example, if the current project has Mocha in its dependencies, just write it directly'mocha test'That's it. {"test": "mocha test"} is the same as {"test": "./node_modules/.bin/mocha test"}
Copy the code
Query certain packages for global installation and non-global installation
  • Non-global installation
1.For non-global installations, we need to configure scripts in the scripts TAB when we want to execute ESLint, for examplescripts: {"eslint-version":"eslint --version"}, just execute'npm run eslint-version'Please refer to the above section for specific reasons"Third way to execute projects internally."About the content of the2.If you don't want to configure it'scripts'Other methods of execution" .\node_modules\.bin\eslint.cmd --version"Run directly"node_modules\.bin"File under the script or'node .\node_modules\eslint\bin\eslint.js --version'Go directly to the directory where the script is runningCopy the code
  • Global Installation
1.Install some packages globally for example'eslint'Direct execution'eslint'This is because you automatically add a shell script to the node file directory during global installation, and the Node path is in the system path so you can call it directly2.What is the'PATH'The environment variable is to tell the system, when the system is asked to run a program without telling it the full path of the program, the system in addition to the current directory to look for the program, and what directory to look for.Copy the code
  • The global path

  • The instructions that can be used in this path take my machine as an example

  • Take a look inside this script (actually executing the bin file eslint directive under global node_modules)

The wildcard

1.Since NPM scripts are Shell scripts, Shell wildcards can be used. When we write script commands, we often need to match files, which uses the wildcard of the path. In general, * represents any string, represented in a directory1Level directory, ** indicates0Level or multilevel directories, for example:1.1. src/* : any file in the SRC directory, matching SRC /a.js; SRC/b.j son; SRC /aa/a.js 1.2. SRC /*.js: SRC does not match any js files in the SRC directory, which matches SRC /a.js; SRC /b.json; SRC/aa/a. s 1.3. The SRC / * /*.js: any js file at the next level of the SRC directory, matching SRC /aa/a.js; SRC /a.js; src/a/aa/a.js1.4. src/ * * /*.js: any js file in the SRC directory, matching SRC /a.js; src/a/a.js; src/a/aa/a.jsCopy the code

The ginseng

1.So here's an example of what we use'vuecli'When in the current project'node_moduels/.bin'Take a look at the execution script figure and make sure you understand it here'npm run 'In executing the corresponding'scripts'It is the corresponding execution window that calls in response to the command, not the NPM that calls it. It is the NPM that calls the shell instructions to the execution window'vue-cli-service'When executed, node actually executes,'node'Can pass when called'process.argv'Gets an array of returns2.about'process.argv'This array contains the command line arguments for starting the Node process. The first element is the absolute pathname of the executable file that started the Node process, process.execPath, and the second element is the path of the currently executing JavaScript file. The remaining elements are other command line arguments. The following figure3.To analyze a set of instructions"scripts": {
  "serve": "vue-cli-service serve --mode=dev --mobile -config build/example.js"} when performing'npm run serve'The actual implementation is'node "node_modules/@vue\cli-service\bin\vue-cli-service.js --mode=dev --mobile -config build/example.js" 'Vue-cli-service. js This JS program theoretically only needs to be executed'process.argv'The print result that can be obtained by passing parameters is as follows: ['/ usr/local/Cellar/node / 7.7.1 _1 / bin/node'.'/Users/mac/Vue-projects/hao-cli/node_modules/.bin/vue-cli-service'.'serve'.'--mode=dev'.'--mobile'.'-config'.'build/example.js'In fact, many command line packages rely on parsers such as Minimist or Yargs to parse command-line arguments. One of the'vue-cli-service 'For example, internal use'minimist'Parse itCopy the code
  • Vue cli – service script

  • Run a Node file

conclusion
1.NPM itself is run through Node and the passing of parameters during the run script phase is actually used'process'This parameter is used to do the following script configuration in'spricts'NPM creates a lot when run in'npm_package_'Prefix, add to'process.env'If you read the following article for more information, you can also see that the parameters passed through Vuecli are also added to'process.env. A custom 'Variable to store1.1.'NPM internal variable': When we execute the NPM command, we add the package.json argument to the process.env variable with the npm_package_ prefix. So the node code above can use process.env.npm_package_name to get the name attribute configured in package.json.1.2.'NPM command parameters'When we run NPM commands, we take arguments with a double dashes suffix: NPM --xx=xx, NPM adds xx to the process.env variable with the npm_config_ prefix. Npm_config_env (NPM run node --env=npmEnv); if NPM run node --env is not specified, the default value is NPM run node --envtrue
1.3.'Script parameters'Js --env=node. This is a pure node command. You can use process.argv to get the node command arguments. The second is the path to the execution file, followed by other parameters separated by Spaces,Copy the code

  • NPM run env
1.When the NPM run script is executed, NPM sets some special env environment variables. All fields in package.json are set to environment variables starting with npM_package_.`npm`All related configurations will also be set to`npm_config_`Take an example of the environment variable at the beginning {"name": "sh"."version": 1.1.1 ""."description": "shenhao"."main": "index.js"."repository": {
    "type": "git"."url": "git+ssh://[email protected]/xxxx/sh.git"}} Process.env.npm_package_name = package.json Git can also be repository_type for the nested property type by going to process.env.npm_package_repository_typeCopy the code
I’d like to know more

Of the process. The env

I want to know more about Vuecli

Multi-command execution

Of course commands can be executed not just one but multiple times in some order1.Serial execution requires that the next task can be executed only after the previous task has been successfully executed, using && symbols to connect. npm run script1 && npm run script22.Parallel execution, where multiple commands can be executed in parallel at the same time, using the ampersand symbol. npm run script1 & npm run script2Copy the code

hook

1.NPM scripts have pre and POST hooks, one before and one after execution. For example, I want to add hooks to the server script I defined in scripts, respectively, before the original directive'pre''post'The prefix"scripts": {
  "preserve": "xxxxx"."serve": "vue-cli-service serve"."postserve": "xxxxxx"} When the NPM run serve command is executed, NPM run preserve, NPM run serve, and NPM run postserve are executed in sequence2.It is often found that we do not specify it and silently skip it. If you want to specify hooks, you must follow them strictly'pre'and'pos'T prefix to add3.'process.env.npm_lifecycle_event'Can be used with hooksconst event = process.env.npm_lifecycle_event
    if (event === 'preserve') {
        console.log('Running the preserve task! ')}else if (_event === 'serve') {
        console.log('Running the serve task! ')}Copy the code

Refer to the article

Npm-run-script – Zhihu (zhihu.com)

Basic usage and the principle of NPM | (10000 +) – long bytes long programming (mmbyte.com)

NPM Scripts – Ruanyifeng.com

NPM package.json properties

About the version

Package. The json guide

Front-end Engineering – Analysis of NPM package management mechanism (juejin. Cn)

Front-end engineering (5) : All the NPM knowledge you need is here