如何检测由于运行“npm install”而执行“prepublish”脚本的时间

Gaj*_*jus 2 node.js npm

https://docs.npmjs.com/misc/scripts

prepublish:在发布包之前运行。(也可以在本地 npm install 上运行,无需任何参数。)

我希望我的脚本仅在用户执行的情况下执行npm publish。但是,如果用户运行“npm install”,NPM 将执行“prepublish”脚本。

Gaj*_*jus 5

我发现的唯一方法是使用 NPM 内部 ENV 变量:

// NPM will run prepublish script after `npm install` (https://docs.npmjs.com/misc/scripts)
// This ensures that when script is executed using `npm *` it is run only when the command is `npm publish`.
if (process.env.npm_config_argv) {
    let npmConfigArgv;

    npmConfigArgv = JSON.parse(process.env.npm_config_argv);

    if (npmConfigArgv.original[0] !== 'publish') {
        console.log('`bundle-dependencies prepublish` will not execute. It appears that `prepublish` script has been run by `npm install`.');

        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

看来 NPM 将原始命令存储在process.env.npm_config_argv变量中。

如果您想知道,每个 NPM 脚本都在不同的进程中运行。因此,在脚本中设置自定义 ENV 变量之类的方法preinstall不起作用。