package.json:如何测试node_modules是否存在
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
。使用哪个 npm script 是您的选择。如果您的应用程序通过 npm start
(良好做法)启动,请使用 start
脚本添加您的检查:
"scripts": { "start" : "./test.sh" }
目录的实际测试可以通过 shell 脚本或 NodeJs 脚本实现,考虑使用 npx
,如 中所述。
根据 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",
}
谢谢!
使用此脚本,我的项目目录的子文件夹 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);
}
我想我会 post 我为跨平台单行条件 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",
}
在package.json里面,是否可以测试node_modules
目录是否存在?
我的目标是在 node_module
不存在时打印一条消息,例如:
node_module not existent: use npm run dist
其中 dist
是我 package.json 的 scripts
中的一个脚本。
谢谢。
是的,通过 npm scripts
。使用哪个 npm script 是您的选择。如果您的应用程序通过 npm start
(良好做法)启动,请使用 start
脚本添加您的检查:
"scripts": { "start" : "./test.sh" }
目录的实际测试可以通过 shell 脚本或 NodeJs 脚本实现,考虑使用 npx
,如
根据 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",
}
谢谢!
使用此脚本,我的项目目录的子文件夹 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);
}
我想我会 post 我为跨平台单行条件 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",
}