簡體   English   中英

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": {
    "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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM