[英]package.json: how to test if node_modules exists
Inside package.json , is it possible to test if node_modules
directory exists?在package.json内部,是否可以测试node_modules
目录是否存在? My goal is to print a message if node_module
does not exists, something like:如果node_module
不存在,我的目标是打印一条消息,例如:
node_module not existent: use npm run dist
where dist
is a script inside scripts
of my package.json.其中dist
是我的 package.json scripts
中的脚本。 Thank you.谢谢你。
I thought I would post what I've done for cross-platform one-liner conditional NPM scripts.我想我会发布我为跨平台单行条件 NPM 脚本所做的事情。
"scripts": {
"start":"(node -e \"if (! require('fs').existsSync('./node_modules'))
{process.exit(1)} \" || echo
'node_module dir missing: use npm run dist') && node start-app.js",
}
Yes it is, via npm scripts
.是的,通过 npm scripts
。 Which npm script to use is your choice.使用哪个npm 脚本是您的选择。 If your application starts via npm start
(good practice) use the start
script to add your check:如果您的应用程序通过npm start
(良好实践)使用start
脚本添加您的检查:
"scripts": { "start": "./test.sh" }
The actual test for the directory can be implemented via a shell script or a NodeJs script, consider using npx
as discussed in Difference between npx and npm?目录的实际测试可以通过 shell 脚本或 NodeJs 脚本来实现,考虑使用npx
中讨论的npx 和 npm 的区别? . .
As suggested by BM in comments, I've created the following script named checkForNodeModules.js
:正如 BM 在评论中所建议的那样,我创建了以下名为checkForNodeModules.js
的脚本:
const fs = require('fs');
if (!fs.existsSync('./node_modules'))
throw new Error(
'Error: node_modules directory missing'
);
And inside my package.json
:在我的package.json
里面:
"scripts": {
"node-modules-check": "checkForNodeModules.js",
"start": "npm run node-modules-check && node start-app.js",
}
Thanks!谢谢!
With this script I have run yarn install
in subfolder app
of my project dir (if node_modules not exist)使用此脚本,我在项目目录的子文件夹app
中运行了yarn install
(如果 node_modules 不存在)
const fs = require('fs');
const path = require('path');
const spawn = require('cross-spawn');
if (!fs.existsSync(path.resolve(__dirname, '../app/node_modules'))) {
const result = spawn.sync(
'yarn',
['--cwd', path.resolve(__dirname, '../app'), 'install'],
{
stdio: 'inherit'
}
);
console.log(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.