package文件scripts解析

npm 是怎样处理scripts 字段的

npm 支持的package.json 文件的“scripts”属性, 可以有以下属性:

prepublish: Run BEFORE the package is packed and published, as well as on local npm install without any arguments. (See below)
prepare: Run both BEFORE the package is packed and published, on local npm install without any arguments, and when installing git dependencies (See below). 在prepublish后运行, 但是在 prepublishOnly前面运行.
prepublishOnly: Run BEFORE the package is prepared and packed, ONLY on npm publish. (See below.)
prepack: run BEFORE a tarball is packed (on npm pack, npm publish, and when installing git dependencies)
postpack: Run AFTER the tarball has been generated and moved to its final destination.
publish, postpublish: Run AFTER the package is published.
preinstall: Run BEFORE the package is installed
install, postinstall: Run AFTER the package is installed.
preuninstall, uninstall: Run BEFORE the package is uninstalled.
postuninstall: Run AFTER the package is uninstalled.
preversion: Run BEFORE bumping the package version.
version: Run AFTER bumping the package version, but BEFORE commit.
postversion: Run AFTER bumping the package version, and AFTER commit.

pretest, test, posttest: Run by the npm test command.
prestop, stop, poststop: Run by the npm stop command.
prestart, start, poststart: Run by the npm start command.
prerestart, restart, postrestart: Run by the npm restart command. Note: npm restart will run the stop and start scripts if no restart script is provided.
preshrinkwrap, shrinkwrap, postshrinkwrap: Run by the npm shrinkwrap command.

Additionally, arbitrary scripts can be executed by running npm run-script <stage>. Pre and post commands with matching names will be run for those as well (e.g. premyscript, myscript, postmyscript). Scripts from dependencies can be run with npm explore <pkg> -- npm run <stage>.

package.json vars

如果依赖于某些模块的可执行脚本,这些可执行的内容会被加到PATH里,
{ "name" : "foo"
, "dependencies" : { "bar" : "0.1.x" }
, "scripts": { "start" : "bar ./test" } }
如上,当执行npm start时,会执行bar脚本,bar脚本会在执行npm install时暴露在node_modules/.bin;

package.json 里定义的字段可以使用npm_package_前缀访问;例如,上面的json中,npm_package_name环境变量会被设置为foo,
可以在代码里访问process.env.npm_package_name;

可以使用npm_config_xx,访问npm congfig 内容;package.json里也可以加congfig字段,但是会被npm config set xx覆盖;

npm_lifecycle_event 设置了当前执行阶段;

注意,以上变量的访问都要使用npm run xxx运行才可以访问到;

hook scripts

如果想在指定的阶段对所有package运行指定的脚本,可以使用hook 脚本;
在node_modules/.hooks/{eventname} 下放置一个可执行文件即可;
hook脚本的运行方式和package.json里的script运行方式一样;在单独的子进程运行;