在 package.json 内部,是否可以测试node_modules
目录是否存在?
我的目标是在node_module
不存在时打印一条消息,例如:
node_module not existent: use npm run dist
其中dist
是我package.json的scripts
中的脚本。
谢谢。
答案 0 :(得分:1)
是的,通过npm scripts
。您选择使用哪个npm script。如果您的应用程序通过npm start
(良好做法)启动,请使用start
脚本添加您的支票:
"scripts": { "start" : "./test.sh" }
可以通过Shell脚本或NodeJs脚本来实现目录的实际测试,请考虑使用Difference between npx and npm?中讨论的npx
。
答案 1 :(得分:0)
正如B M在评论中建议的那样,我创建了以下名为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",
}
谢谢!
答案 2 :(得分:0)
使用此脚本,我在项目目录的子文件夹 yarn install
中运行了 app
(如果 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);
}