【问题标题】:package.json: how to test if node_modules existspackage.json:如何测试 node_modules 是否存在
【发布时间】:2020-02-02 12:57:30
【问题描述】:

package.json里面,是否可以测试node_modules目录是否存在? 如果node_module 不存在,我的目标是打印一条消息,例如:

node_module not existent: use npm run dist

其中dist 是我的package.json 的scripts 内的一个脚本。 谢谢。

【问题讨论】:

    标签: node.js npm npm-scripts npm-run


    【解决方案1】:

    是的,通过 npm scripts。使用哪个npm script 是您的选择。如果您的应用程序通过 npm start 启动(良好做法),请使用 start 脚本添加您的检查:

    "scripts": { "start" : "./test.sh" }

    目录的实际测试可以通过 shell 脚本或 NodeJs 脚本实现,请考虑使用npx,如Difference between npx and npm? 中所述。

    【讨论】:

    • 我看到两个问题:在类 Unix 系统上 test.sh 可以运行,但在 Windows 系统上不会; npx 执行 npm 二进制文件,但是在时间 0,我没有 node_modules 目录,那么要运行什么可执行文件,一个全局的?如果安装全新节点的同事没有全局可执行文件怎么办?
    • 如果您需要独立于平台的解决方案,npx 将是更好的选择。它会根据要运行的命令的名称来安装软件包。
    • 抱歉,我需要一个 sn-p 来更好地理解这一点。那么在"scripts" 部分里面写什么呢?类似"test": "npx what?
    • 可能最简单的解决方案,不需要npx"scripts": { "start" : "node test.js && node start-app.js" },而在test.jsif (! fs.existsSync('./node_modules')) throw new Error('node_modules not found...');。我个人认为运行npm install 应该在其他地方解决,例如。 G。在 CI/CD 管道中,但从技术上讲,这应该可行。
    • 谢谢 B M,这正是我正在寻找的!
    【解决方案2】:

    根据 cmets 中 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",
    }
    

    谢谢!

    【讨论】:

      【解决方案3】:

      使用此脚本,我在项目目录的子文件夹 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);
      }
      

      【讨论】:

        【解决方案4】:

        我想我会发布我为跨平台单行条件 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",
        }
        

        【讨论】:

        • 聪明,不完全适合 OP,但在增加价值时不管怎样都赞成。
        • 也就是说,考虑更改硬编码值./bin/helpers 以及setup-helpersnpm run final-build-step 以匹配手头的原始问题。
        猜你喜欢
        • 2018-10-25
        • 2021-03-04
        • 1970-01-01
        • 2020-05-05
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多