簡體   English   中英

如何識別我的項目中是否安裝了npm軟件包

[英]How to identify npm packages installed or not in my project

我正在嘗試使用nodejs在我的角度項目中找到已安裝或未安裝的npm軟件包。 如何從package.json獲取已安裝的軟件包以進行檢查。 我有一個帶有包裝的陣列。 例:

var npmpackagesarr=["example-ng6-input","example-ng6-radio","example-ng6-combo"];

   for(var i=0;i<npmpackagesarr.length;i++){

    if(npmpackagesarr[i]=="????"){
      console.log("Hey..this package already installed");
    }
    else{
      console.log("Hey..this package not installed");
    }

   }

如何確定陣列npm軟件包是否已安裝?

打開文件項目並檢查Package.json文件,否則檢查node_modules。

您可以打開Package.json並查看依賴項,或使用npm install在依賴項中安裝所有軟件包。

使用Package.json上的JSON.parse並將依賴項鍵提取到數組中。 之后,您可以使用要查找的值在該數組上運行indexOf。

let data;
fetch('./Package.json').then(data => {
  data = Object.keys((JSON.parse(res)).dependencies);
})

search(array, package) {
  if(array.indexOf(package) !== -1) {
    // installed
  } else {
    // not installed message
  }
}

search(data, '@angular/core');

這是一個腳本,用於檢查預定義列表中的每個軟件包是否都在package.json定義並已安裝。

const fs = require('fs');

const PACKAGES = ['aws-sdk', 'node-cache', 'example-ng6-input', 'lorem-hipsum'];

const readJSONFile = (name) => {
  try {
    return JSON.parse(fs.readFileSync(name, 'utf8'));
  } catch (error) {
    return {};
  }
};

const isDepMissing = ({ name, json }) => {
  const d1 = json.dependencies || {};
  const d2 = json.devDependencies || {};
  return !(d1[name] || d2[name]);
};

const packageJSON = readJSONFile('package.json');
const packageLockJSON = readJSONFile('package-lock.json');

const notDefined = PACKAGES.filter(name => isDepMissing({ name, json: packageJSON }));
const notInstalled = PACKAGES.filter(name => isDepMissing({ name, json: packageLockJSON }));

console.log('the following packages are not defined:', notDefined);
console.log('the following packages are not installed:', notInstalled);

這將devDependencies package.jsonpackage-lock.json dependenciesdevDependencies ,並打印PACKAGES中找不到的任何內容。

假設您使用的節點版本足夠現代,因此可以編寫package-lock.json

您可以將NCU用於相同的功能。

它具有各種此類命令,可以幫助您實現目標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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