[英]package.json: how to test if node_modules exists
在package.json内部,是否可以测试node_modules
目录是否存在? 如果node_module
不存在,我的目标是打印一条消息,例如:
node_module not existent: use npm run dist
其中dist
是我的 package.json 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",
}
是的,通过 npm scripts
。 使用哪个npm 脚本是您的选择。 如果您的应用程序通过npm start
(良好实践)使用start
脚本添加您的检查:
"scripts": { "start": "./test.sh" }
目录的实际测试可以通过 shell 脚本或 NodeJs 脚本来实现,考虑使用npx
中讨论的npx 和 npm 的区别? .
正如 BM 在评论中所建议的那样,我创建了以下名为checkForNodeModules.js
的脚本:
const fs = require('fs');
if (!fs.existsSync('./node_modules'))
throw new Error(
'Error: node_modules directory missing'
);
在我的package.json
里面:
"scripts": {
"node-modules-check": "checkForNodeModules.js",
"start": "npm run node-modules-check && node start-app.js",
}
谢谢!
使用此脚本,我在项目目录的子文件夹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.